Tom*_*ola 8 android bluetooth broadcastreceiver
我想听一些特定的蓝牙设备的连接/断开连接,这些设备的MAC地址我知道,但不一定配对(我不想弄乱用户的配对设备列表,反之亦然).我只对发现他们的存在感兴趣,而不是与他们沟通.
这适用于我的下面的代码!但我的问题是,我无法找出哪个特定设备正在连接/断开连接,只是它发生在某人身上.我怎样才能找出行动涉及哪一个?
首先,我为我的两个特定物理蓝牙设备实例化对象,并将它们添加到我的intent过滤器:
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);
Run Code Online (Sandbox Code Playgroud)
然后我听他们的广播:
final BroadcastReceiver intentReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Run Code Online (Sandbox Code Playgroud)
现在我想知道哪一个已连接和/或断开连接,我不知道如何做到这一点.
1)我直接使用"BluetoothDevice".它对广播的反应很好,但它并没有告诉我这两个物理设备中的哪一个涉及行动.他们是一种找出方法吗?不允许使用Bluetooth.getName(),因为它不是静态类.
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
}
Run Code Online (Sandbox Code Playgroud)
或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 ");
Run Code Online (Sandbox Code Playgroud)
但是它记录了它与myPinkHeadset的连接,即使它是myPvBluetoothDongle我是物理激活的.它始终适用于if测试中的第一个.它只关心行动本身,而不关心它涉及哪个对象.
我看到EXTRA_DEVICE"被用作此类广播的每个意图中的Parcelable BluetoothDevice额外字段." 但它只返回null给我:
String extra = intent.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
Run Code Online (Sandbox Code Playgroud)
Tom*_*ola 16
这使设备连接到:
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Run Code Online (Sandbox Code Playgroud)
作为一个新手,我误解了可以理解的概念.EXTRA_DEVICE是一个String,但它只是该对象的标记.因此,无需注册或收听BluetoothDevice的各个实例.当广播动作时,意图将告知哪个物理设备引起了该动作.(我可以为此自己+1 :-D)
| 归档时间: |
|
| 查看次数: |
4316 次 |
| 最近记录: |