其他分享
首页 > 其他分享> > android-如何接收蓝牙设备工作的意图?

android-如何接收蓝牙设备工作的意图?

作者:互联网

我正在尝试让我的应用程序的服务侦听蓝牙连接和断开连接的尝试,因此我可以动态检查/支持蓝牙网络共享网络通信.

首先,我有两个三星S4(运行CyanogenMod 10.2,它基于Android 4.3.1),可以很好地配对.如果我将一台设备设置为蓝牙系绳,则当另一台设备连接时,将创建一个新的bt-pan网络接口,并使用DHCP分配IP.我在外壳中使用iwconfig和ifconfig确认了这一点.

我的应用程序中存在以下权限:(还有更多,我只是指出我添加的BT权限)

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

这是我的服务的onCreate,我在其中设置了IntentFilters :(请注意,我在这里已经有Toasts了,但是我原来是在使用Logging的)

@Override
public void onCreate() {
    super.onCreate();
    ...     
    this.mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);

    mLocalBroadcastManager.registerReceiver(mMessageReceiver, filter);
}

这是我的BroadcastReceiver实现:

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action.equals(BluetoothDevice.ACTION_FOUND)) {
            Toast.makeText(getApplicationContext(), "BT found", Toast.LENGTH_SHORT).show();
        } else if(action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
            Toast.makeText(getApplicationContext(), "BT Connected", 
        } else if(action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
            Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
        } else
            Toast.makeText(getApplicationContext(), "BT Disconnect requested", Toast.LENGTH_SHORT).show();
        }
    }
}

现在,当我打开/关闭蓝牙,连接/断开与配对设备的连接时,什么也不会触发.我已经从两端为设备买单了.没有广播.

有人有建议吗?我真的需要接收这些蓝牙事件.请不要指向具有相同权限和意图过滤器的其他帖子/站点.谢谢.

解决方法:

我有一个非常相似的代码可以工作,我发现的唯一主要区别是:

mLocalBroadcastManager.registerReceiver(mMessageReceiver, filter);

我相信应该从想要获取意图的上下文中调用registerReceiver.
尝试从此调用方法.即删除mLocalBroadcastManager,如:

registerReceiver(mMessageReceiver, filter);

标签:android-bluetooth,android
来源: https://codeday.me/bug/20191122/2057940.html