我正在尝试让我的应用程序的服务侦听蓝牙连接和断开连接的尝试,因此我可以动态检查/支持蓝牙网络共享网络通信.
首先,我有两个三星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);