android 蓝牙状态变化,【Android】监听蓝牙状态变化

【关键词】

广播 LocalBroadcastManager 监听蓝牙状态

【问题】

广播的用法;

使用 LocalBroadcastManager 注册蓝牙广播,接收不到消息;

【解决方案】

在自定义广播的时候才使用 LocalBroadcastManager,并且需求是:广播只在本 APP 中有效;

不要尝试通过 LocalBroadcastManager 操作(注册,取消注册,发送)系统的广播;

【权限】

【注册】

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 vs Context.registerReceiver(), Context.sendBroadcast(Intent), and Context.unregisterReceiver() are they same?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值