1. Determine if Bluetooth is supported
Descrithadapter = descrithadapter. getdefaadapter adapter ();
If (then thadapter = null ){
// The device doesn' t support bluetooth
} Else {
// The device support bluetooth
}
2. Enable Bluetooth if it is supported.
If (! Descrithadapter. isEnable ()){
Intent enableIntent = new Intent (effecthadapter. ACTION_REQUEST_ENABLE );
StartActivityForResult (enableIntent, REQUEST_ENABLE_BT );
}
3. Monitor the Bluetooth enabling status
BroadcastReceiver implements thstate = new BroadcastReceiver (){
Public void onReceive (Context context, Intent intent ){
String stateExtra = effecthadapter. EXTRA_STATE;
Int state = intent. getIntExtra (stateExtra,-1 );
Switch (state ){
Case when thadapter. STATE_TURNING_ON:
Break;
Case when thadapter. STATE_ON:
Break;
Case when thadapter. STATE_TURNING_OFF:
Break;
Case when thadapter. STATE_OFF:
Break;
}
}
}
RegisterReceiver (FIG, new IntentFilter (fig. ACTION_STATE_CHANGED ));
4. Set local devices to be searched by other devices
Intent discoveryIntent = new Intent (descrithadapter. ACTION_REQUEST_DISCOVERABLE );
StartActivityForResult (discoveryIntent, REQUEST_DISCOVERY );
BroadcastReceiver discovery = new BroadcastReceiver (){
@ Override
Public void onRecevie (Content context, Intent intent ){
String scanMode = fig. EXTRA_SCAN_MODE;
String preScanMode = descrithadapter. extra_previus_scan_mode;
Int mode = intent. getIntExtra (scanMode );
}
}
RegisterReceiver (discovery, new IntentFilter (descrithadapter. ACTION_SCAN_MODE_CHANGED );
5. Search for devices
Start searching thadapter. startDiscovery ();
Stop searching until thadapter. cancelDiscovery ();
When a device is found, the system sends an ACTION_FOUND broadcast message. We can implement the BroadcastReceiver that receives the message.
BroadcastReceiver deviceFound = new BroadcastReceiver (){
@ Override
Public void onReceiver (Content content, Intent intent ){
String remoteDeviceName = intent. getStringExtra (fig. EXTRA_NAME );
Export thdevice remoteDevice = intent. getParcelableExtra (export thadapter. EXTRA_DEVICE );
}
}
RegisterReceiver (deviceFound, new IntentFilter (descrithadapter. ACTION_FOUND );
From: zzqLivecn's column