问题
I would like to delete paired bluetooth low energy devices with names that start with "ABC" on an Android phone programatically.
I am using Android studio.
回答1:
To unpair all devices use this code
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
try {
if(device.getName().contains("abc")){
Method m = device.getClass()
.getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
}
} catch (Exception e) {
Log.e("fail", e.getMessage());
}
}
}
回答2:
If you are specific about BLE(bluetooth low energy), To get all bonded devices you can write a method as.
public List<BluetoothDevice> getConnectedDevices() {
BluetoothManager btManager = (BluetoothManager)getSystemService(BLUETOOTH_SERVICE);
return btManager.getConnectedDevices(BluetoothProfile.GATT);
}
This return the list of BLE devices connected in GATT profile. Fetch the name confirm if this the device you want to disconnet as:
List<BluetoothDevice> btdevices = getConnectedDevices();
for(int i=0;i<btdevices.size();i++)
{
//match your device here
Log.d("saurav"," BLE Name:"+btdevices.get(i).getName());
}
To disconnect you can simply call disconnect method. You need disconnect with gatt instance(Same gatt instance you used to connect the BLE device).
public void disconnect() {
if (gatt == null) {
return;
}
gatt.disconnect();
}
This will disconnect your BLE device. I have teste tshi personally and working for me.
来源:https://stackoverflow.com/questions/39531986/delete-all-paired-bluetooth-devices-on-android