Android Scan Bluetooth device is an asynchronous process, the core step is: Call Bluetoothadapter startdiscovery () for device scanning, the results of the scan through the broadcast receive processing! Specific as follows:
1. Application of the relevant authority
1 < android:name= "Android.permission.BLUETOOTH_ADMIN"/>2 <android:name= "Android.permission.BLUETOOTH"/>
2. Register for the broadcast
1 Private voidRegisterbroadcast () {2 //Register for broadcasts when a device is discovered3Intentfilter filter =NewIntentfilter (bluetoothdevice.action_found);4 Mcontext.registerreceiver (mreceiver, filter);5 6 //Register for broadcasts when discovery have finished7Filter =NewIntentfilter (bluetoothadapter.action_discovery_finished);8 Mcontext.registerreceiver (mreceiver, filter);9}
3. Scanning equipment
1 Private voidDodiscovery () {2 //If we ' re already discovering, stop it3 if(Mbluetoothadapter.isdiscovering ()) {4 mbluetoothadapter.canceldiscovery ();5 }6 //Request discover from Bluetoothadapter7 mbluetoothadapter.startdiscovery ();8}
4. Processing the scanned device in the broadcast
1 Private FinalBroadcastreceiver Mreceiver =NewBroadcastreceiver () {2 @Override3 Public voidOnReceive (Context context, Intent Intent) {4String action =intent.getaction ();5 6 if(BluetoothDevice.ACTION_FOUND.equals (ACTION)) {7 //TODO Discovery finds a device8 9}Else if(bluetoothadapter.action_discovery_finishedTen . Equals (action)) { One //TODO Discovery is finished A } - } -};
Android Scan Bluetooth device