安卓本地广播:简单介绍LocalBroadcastManager的使用

本地广播的优势:

本地广播较之普通的广播更加安全,发出的广播只能在当前APP中能够接收到,其他APP无法接收。

使用介绍:

1.发广播:

        Intent intent = new Intent();
        intent.setAction(Constants.ANSWERED_RECEIVER_ACTION);//自定义action
        LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);

2.接收广播:

1.实现BroadCastReceiver类:

private class AnsweredReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            postPaperRecord(examPaperBean);
            LocalBroadcastManager.getInstance(context).unregisterReceiver(answeredReceiver);
        }
    }

2.注册该广播接收器:

            answeredReceiver = new AnsweredReceiver();
            IntentFilter filter = new IntentFilter(Constants.ANSWERED_RECEIVER_ACTION);
            LocalBroadcastManager.getInstance(this).registerReceiver(answeredReceiver,filter);

3.注销该广播接收器:

LocalBroadcastManager.getInstance(context).unregisterReceiver(answeredReceiver);

使用方式跟普通的广播类似,看一遍基本就会用了。

如果有疑问给我留言,会尽快回复。

欢迎参观博主的其他博客。





你可能感兴趣的:(android常用记录)