Android清除已配对蓝牙列表

本文介绍如何根据项目需求清除Android设备上已配对的蓝牙列表,主要涉及相关的关键代码实现。

项目需求清除已配对过的蓝牙列表,主要代码

Method m = device.getClass()
        .getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
开发初期能正常清除已配对蓝牙列表,但在测试过程中发现就只是我手上的测试机能每次清除成功,其他类如iPhone、蓝牙音箱等,有很高的概率清除不了!各种懵逼各种debug,最后发现清除已配对列表之前必须要保证蓝牙是处于打开的状态,且不能打开后蓝牙后 立即进行清除操作!

private static void removePairDevice() {
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
        mBluetoothAdapter.enable();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    if (mBluetoothAdapter != null) {
        Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();
        for (BluetoothDevice device : bondedDevices) {
            unpairDevice(device);
        }
    }
}

private static void unpairDevice(BluetoothDevice device) {
    try {
        Method m = device.getClass()
                .getMethod("removeBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
}

本人采用提前开启蓝牙的方式解决的这个问题,规避sleep 3秒这个不友好的操作。


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值