1. check whether a device has a bluetooth device. Enable the bluetooth device to obtain the paired device.
These operations require Permissions
<Uses-Permission Android: Name = "android. Permission. Bluetooth"/>
The following is to determine whether there is a bluetooth device, whether to enable Bluetooth, if not, request to enable Bluetooth
Descrithadapter BA = descrithadapter. getdefaadapter adapter (); If (null! = BA) {system. Out. println ("the local device has a bluetooth device"); If (! Ba. isenabled () {intent = new intent (effecthadapter. action_request_enable); startactivity (intent); // or BA. enable (); // disable the same WiFi as Ba. disable ();}}
The following code gets the paired bluetooth device
Set<BluetoothDevice> device=ba.getBondedDevices(); if(device.size()>0){ for(BluetoothDevice bd:device){System.out.println(bd.getAddress()+bd.getName());}}
2. Set the visible time of Bluetooth to be detected and connected by other devices. <uses-Permission Android: Name = "android. Permission. effecth_admin"/>
Set the visible time of Bluetooth
Intent intentvisible = new intent (effecthadapter. action_request_discoverable); intentvisible. putextra (effecthadapter. extra_discoverable_duration, 400); // The default value is 120 seconds. If the value exceeds 300 seconds, it will be set to 300. but on my device, it can be 2400. API error? This. startactivity (intentvisible );
3. Get the scanned Device
Permission required <uses-Permission Android: Name = "android. Permission. Permission th_admin"/>
Code to start scanning
BluetoothAdapter ba=BluetoothAdapter.getDefaultAdapter();ba.startDiscovery();
It takes 12 seconds, and the power consumption is high. When a broadcast is scanned, a broadcast message is sent and a broadcast is registered to receive the message.
class MyReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {BluetoothDevice bd=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);Toast.makeText(BluetoothActivity.this, bd.getName(), Toast.LENGTH_SHORT).show();} }
Register this broadcast
IntentFilter intentfilter=new IntentFilter(BluetoothDevice.ACTION_FOUND); MyReceiver mr=new MyReceiver(); this.registerReceiver(mr, intentfilter);
Register a scanned broadcast:
class FinishFound extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {BluetoothActivity.this.unregisterReceiver(this);BluetoothActivity.this.unregisterReceiver(mr);} }
Disable the broadcast that scans for Bluetooth notifications in this broadcast and disable yourself.
I won't talk about registering this broadcast.
Download project: Click to download