项目需求清除已配对过的蓝牙列表,主要代码
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秒这个不友好的操作。
本文介绍如何根据项目需求清除Android设备上已配对的蓝牙列表,主要涉及相关的关键代码实现。

3099

被折叠的 条评论
为什么被折叠?



