第一行代码-5.4 使用本地广播

  使用前面所说的广播的范围是全局的,一个应用程序发送的广播可能被其他程序截获,所以Android还定义了另一种广播:本地广播,只能被本程序接收的广播。实现起来也不难,用LocalBroadcastManager就行了。

private IntentFilter filter;
    private LocalBroadcastManager localBroadcastManager;
    private LocalReceiver localReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        localBroadcastManager = LocalBroadcastManager.getInstance(MainActivity.this); // 获取实例

        mButton = (Button) findViewById(R.id.send_broadcast_button);
        mButtonLocal = (Button) findViewById(R.id.send_localbroadcast_button);
        mButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent();
                intent.setAction("static_broadcast");
                //sendBroadcast(intent);
                sendOrderedBroadcast(intent, null); // 发送有序广播
            }
        });
        mButtonLocal.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
                localBroadcastManager.sendBroadcast(intent);
            }
        });
        filter = new IntentFilter();
        filter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver, filter); // 注册本地广播监听器
    }

    class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "成功接收本地广播!", Toast.LENGTH_LONG).show();
        }
    };

    @Override
    protected void onDestroy() {
        localBroadcastManager.unregisterReceiver(localReceiver);
        super.onDestroy();
    }

  从代码来看,声明和注册的方式和一般的广播类似,只是接收的注册和广播的发送都要通过LocalBroadcastMananger来实现。
  实现效果:

  注意:为什么本地广播不能通过静态的方式注册呢?因为本地广播只能自己的应用接收,所以发送本地广播的时候,程序肯定已经启动了,而静态注册广播的目的就是让程序没有启动的时候,也可以接收到广播。所以,静态注册对于本地广播是没有必要的。
  

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值