【发布时间】:2012-02-27 03:27:45
【问题描述】:
我想监听与我知道其 MAC 地址但不一定配对的一些特定蓝牙设备的连接/断开连接(我不想弄乱用户的配对设备列表,反之亦然)。我只对发现他们的存在感兴趣,而不是与他们交流。
这对我下面的代码非常有效!但我的问题是我无法找出正在连接/断开连接的特定设备,只是它发生在其中的某个人身上。我怎样才能知道该操作涉及哪一项?
首先我为我的两个特定物理蓝牙设备实例化对象并将它们添加到我的意图过滤器中:
BluetoothDevice myPinkHeadset = mBluetoothAdapter.getRemoteDevice("18:17:0C:EB:9C:81");
BluetoothDevice myPcBluetoothDongle = mBluetoothAdapter.getRemoteDevice("5A:7A:CC:4B:C5:08");
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(myPinkHeadset.ACTION_ACL_CONNECTED);
intentFilter.addAction(myPinkHeadset.ACTION_ACL_DISCONNECTED);
intentFilter.addAction(myPcBluetoothDongle.ACTION_ACL_CONNECTED);
intentFilter.addAction(myPcBluetoothDongle.ACTION_ACL_DISCONNECTED);
然后我会收听有关他们的广播:
final BroadcastReceiver intentReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
现在我想知道哪个已连接和/或断开连接,但我不知道该怎么做。
1)我直接使用“BluetoothDevice”。它对广播的反应很好,但它没有告诉我动作涉及两个物理设备中的哪一个。他们是一种找出方法吗?不允许 Bluetooth.getName(),因为它不是静态类。
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
}
或 2) 我在两个设备上都监听这两个操作。
if (myPinkHeadset .ACTION_ACL_CONNECTED.equals(action)) {
Log.v(TAG, "Connected to myPinkHeadset ");
}
else if (myPinkHeadset .ACTION_ACL_DISCONNECTED.equals(action)) {
Log.v(TAG, "Disconnected from myPinkHeadset ");
}
else if (myPcBluetoothDongle .ACTION_ACL_CONNECTED.equals(action)) {
Log.v(TAG, "Connected to myPcBluetoothDongle ");
}
else if (myPcBluetoothDongle .ACTION_ACL_DISCONNECTED.equals(action)) {
Log.v(TAG, "Disconnected from myPcBluetoothDongle ");
但它会记录它与 myPinkHeadset 连接,即使它是我物理激活的 myPvBluetoothDongle。它总是适用于 if 测试中最先出现的那个。它只关心动作本身,而不关心它关心的对象。
我看到 EXTRA_DEVICE 是“在此类广播的每个意图中用作 Parcelable BluetoothDevice 额外字段”。但它只返回 null 给我:
String extra = intent.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
【问题讨论】:
标签: android bluetooth broadcastreceiver