使用LocalBroadcastManager

本文介绍了Android Support包中的LocalBroadcastManager工具,它用于在同一应用的不同组件间发送广播。使用该工具可以确保广播仅限于本应用内部,提高了安全性,并且比全局广播更高效。文章提供了发送和接收广播的具体代码示例。

LocalBroadcastManagerAndroid Support包提供了一个工具,是用来在同一个应用内的不同组件间发送Broadcast的。

 

使用LocalBroadcastManager有如下好处:

  • 发送的广播只会在自己App内传播,不会泄露给其他App,确保隐私数据不会泄露
  • 其他App也无法向你的App发送该广播,不用担心其他App会来搞破坏
  • 比系统全局广播更加高效

发送广播:

final Intent intent = new Intent(UartService.DATAUPDATA);
        LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);

接收广播:

        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
                updateReceiver, makeGattUpdateIntentFilter());

private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UartService.DATAUPDATA);
        return intentFilter;
    }

    private final BroadcastReceiver updateReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            ToastUtil.toast(getActivity(), action);
            
        }
    };

 

转载于:https://www.cnblogs.com/zhaoleigege/p/5497361.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值