1. 程式人生 > >Android 搜尋不到藍芽裝置

Android 搜尋不到藍芽裝置

搜尋不到新裝置裝置

只有已配對裝置

package com.joey.qzhu.simplebluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Set;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int REQUEST_ENABLE_BT = 0x01;

    private Button butOpen;
    private Button butSearch;
    private TextView tvState;
    private TextView tvUnPaired;
    private TextView tvPaired;
    private BluetoothAdapter mBluetoothAdapter;
    private Toast toast;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        butOpen = (Button) this.findViewById(R.id.but_open_bt);
        butSearch = (Button) this.findViewById(R.id.but_search_bt);
        tvState = (TextView) this.findViewById(R.id.tv_state);
        tvUnPaired = (TextView) this.findViewById(R.id.tv_unpaired);
        tvPaired = (TextView) this.findViewById(R.id.tv_paired);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // 驗證裝置是否支援藍芽
        if (mBluetoothAdapter == null) {
            showToast("裝置不支援藍芽");
            return;
        }

        // 註冊廣播接收器
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filter);

        // 開啟藍芽功能
        butOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBluetoothAdapter.isEnabled()) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                }
            }
        });

        // 搜尋藍芽裝置
        butSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBluetoothAdapter.isEnabled()) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                }
                boolean startDiscovery = mBluetoothAdapter.startDiscovery();
                tvState.setText(startDiscovery ? "正在搜尋裝置..." : "搜尋失敗");
            }
        });

        // 獲取已配對裝置
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                tvPaired.setText("");
                tvPaired.append("\n" + device.getName() + " " + device.getAddress() + " " + device.getBondState());
            }
        }
    }

    // 新增廣播接收器
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                tvUnPaired.setText("");
                tvUnPaired.append("\n" + device.getName() + " " + device.getAddress() + " " + device.getBondState());
                showToast("發現裝置");
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                tvState.setText("搜尋完成");
            }
        }
    };

    // 顯示訊息
    private void showToast(String message) {
        toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.joey.qzhu.simplebluetooth">

    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>