【关键词】
广播
LocalBroadcastManager
监听蓝牙状态
【问题】
- 广播的用法;
- 使用 LocalBroadcastManager 注册蓝牙广播,接收不到消息;
【解决方案】
- 在自定义广播的时候才使用 LocalBroadcastManager,并且需求是:广播只在本 APP 中有效;
- 不要尝试通过 LocalBroadcastManager 操作(注册,取消注册,发送)系统的广播;
【权限】
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
【注册】
mContext.registerReceiver(mReceiver, makeFilter());
【注销】
mContext.unregisterReceiver(mReceiver);
【代码】
private IntentFilter makeFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
return filter;
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
LogUtil.e(TAG, "onReceive---------");
switch (intent.getAction()) {
case BluetoothAdapter.ACTION_STATE_CHANGED:
int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
switch (blueState) {
case BluetoothAdapter.STATE_TURNING_ON:
LogUtil.e("onReceive---------STATE_TURNING_ON");
break;
case BluetoothAdapter.STATE_ON:
LogUtil.e("onReceive---------STATE_ON");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
LogUtil.e("onReceive---------STATE_TURNING_OFF");
BleUtil.toReset(mContext);
break;
case BluetoothAdapter.STATE_OFF:
LogUtil.e("onReceive---------STATE_OFF");
BleUtil.toReset(mContext);
break;
}
break;
}
}
};
【参考资料】
LocalBroadcastManager is as its name says, an implementation of the broadcast methods that are only available to your app. This has some benefits, with the biggest being safety, one less hole to watch out for. In terms of implementation, there are a few things to keep in mind:
- This class is from the Android Support Library
- The method calls have to be prefaced with
LocalBroadcastManager.getInstance([CONTEXT])
where[CONTEXT]
is a subclass of the Context class, such as Activity.- When you use this class, it is purely for your app. Using it to register receivers and make broadcasts that are system wide will fail.
So this class is not the same as Context, it is simply a very specific, app-only implementation of Context's receiver/broadcast methods. You should use it when there is absolutely no point for your listener to listen on global (system-wide) broadcasts and when your broadcast does not need to target anything outside your app.