Delete all paired bluetooth devices on Android

↘锁芯ラ 提交于 2021-01-27 19:06:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!