Android 掃描藍牙設備

Android掃描藍牙設備是個異步的過程,核心的步驟爲:調用bluetoothAdapter的startDiscovery()進行設備掃描,掃描的結果經過廣播接收處理!具體以下:android

1.申請相關權限異步

1 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
2     <uses-permission android:name="android.permission.BLUETOOTH"/>

2.註冊廣播ide

1 private void registerBroadcast() {
2         // Register for broadcasts when a device is discovered
3         IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
4         mContext.registerReceiver(mReceiver, filter);
5 
6         // Register for broadcasts when discovery has finished
7         filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
8         mContext.registerReceiver(mReceiver, filter);
9     }

3.掃描設備spa

1 private void doDiscovery() {
2         // If we're already discovering, stop it
3         if (mBluetoothAdapter.isDiscovering()) {
4             mBluetoothAdapter.cancelDiscovery();
5         }
6         // Request discover from BluetoothAdapter
7         mBluetoothAdapter.startDiscovery();
8     }

4.廣播中處理掃描到的設備code

 1 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
 2         @Override
 3         public void onReceive(Context context, Intent intent) {
 4             String action = intent.getAction();
 5             
 6             if (BluetoothDevice.ACTION_FOUND.equals(action)) {
 7                 // TODO discovery finds a device
 8                 
 9             } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
10                     .equals(action)) {
11                 // TODO discovery is finished
12             }
13         }
14     };
相關文章
相關標籤/搜索