Android 掃描藍牙設備


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

1.申請相關權限

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

2.注冊廣播

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.掃描設備

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.廣播中處理掃描到的設備

 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     };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM