简体   繁体   English

删除Android上所有配对的蓝牙设备

[英]Delete all paired bluetooth devices on Android

I would like to delete paired bluetooth low energy devices with names that start with "ABC" on an Android phone programatically. 我想以编程方式删除名称以“ ABC”开头的配对的蓝牙低能耗设备。

I am using Android studio. 我正在使用Android Studio。

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());
                }
            }
        }

If you are specific about BLE(bluetooth low energy), To get all bonded devices you can write a method as. 如果您对BLE(蓝牙低功耗)非常了解,则可以编写一个方法来获取所有绑定的设备。

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. 这将返回在GATT配置文件中连接的BLE设备的列表。 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). 您需要与gatt实例断开连接(用于连接BLE设备的相同gatt实例)。

public void disconnect() {
        if (gatt == null) {
            return;
        }
        gatt.disconnect();

    }

This will disconnect your BLE device. 这将断开您的BLE设备。 I have teste tshi personally and working for me. 我个人有Teste Tshi,为我工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM