问题:当蓝牙设备正在配对或配对时,我会收到通知。但是,我不知道如何在设备未配对时收到通知。我怎样才能让我的应用程序在它与我的设备未配对时识别出来?
示例:假设我通过代码将 Surface 平板电脑和我的 android 手机配对。我的广播接收器将注册ACTION_BOND_STATE_CHANGED
意图并允许我根据需要处理它。现在,如果我想取消配对我的 Surface 平板电脑,我的手机不会收到有关设备已取消配对的通知。如果我检查device.getBondState()
未配对后的设备,它等于BOND_BONDED
(显然不是)我可以让它在我尝试连接到未配对的设备后再次识别它未配对,然后应用程序崩溃然后当我转身时再次打开该应用程序,然后它才会将其识别为未配对。
场景:我BroadcastReceiver
注册了一个监听蓝牙设备引起的意图
getActivity().registerReceiver(broadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
getActivity().registerReceiver(broadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
getActivity().registerReceiver(broadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED));
getActivity().registerReceiver(broadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
我用这个处理这些动作BroadcastReciever
:
final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println("ACTION: "+ action);
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
list();
// Get the BluetoothDevice object from the intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("FOUND: " + device.getName() + " STATE: " + device.getBondState());
mapInput(device);
// Add the name and the mac address of the object to the array adapter
BTSimpleAdapter.notifyDataSetChanged();
} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("UPDATE Name " + device.getName() + " Value " + device.getAddress() + " Bond state " + device.getBondState());
for (Map<String, String> entry : data) {
if (entry.get("Name").equals(device.getName()) && entry.get("Value").equals(device.getAddress())) {
if (device.getBondState() == BluetoothDevice.BOND_NONE) {
entry.put("Paired", "Unpaired");
} else if (device.getBondState() == BluetoothDevice.BOND_BONDING) {
entry.put("Paired", "Pairing");
} else {
entry.put("Paired", "Paired");
}
BTSimpleAdapter.notifyDataSetChanged();
}
}
}
}
};