为了简化注册、发送广播。既然是本地,这个广播的范围相对就小了,但这样比全局的广播有效率得多。同时,这样也确保了你所发送的广播不被其它APP的接受者接收。app
一样的,别的APP的广播(使用LocalManager发出的)也不能发送到你这儿的接收者。ide
那么如何使用呢?this
答:首先你必须确保你引入了Android Support Library。 而后就能够:事件
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);get
那么如何注册接收者呢?
答:与注册全局的相似:同步
lbm.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Handle the received local broadcast
}
}, new IntentFilter(LOCAL_ACTION)); it
发送呢? 答:lbm.sendBroadcast(new Intent(Local_ACTION));io
同时呢,你也能够用此来广播同步的Intent使用sendBroadcastSync.ast
注意:上面所声明的接受者也是能够处理全局的广播Intents。这是什么意思? 答:主要在于你的发送方是否是LocalManager发送的,前面所说的优点都是基于这个管理者,跟接收者没什么关系,是发送方限制了渠道罢了。class
延迟发送的intent。
为何要是延迟发送?
答:pending intent主要是用来回应将来的事件,好比Notification或者Widget被点击后触发。
可是代码又是写在你本身的app里,就好像是你本身app完成的跳转。
PendingIntent 类提供静态方法去构建Pending Intent,用来启动一个activity,service或者广播一个intent.
下面给出一些代码:
int requestCode = 0;
int flags = 0;
// Start an Activity
Intent startActivityIntent = new Intent(this, MyOtherActivity.class);
PendingIntent.getActivity(this, requestCode,
startActivityIntent, flags);
// Start a Service
Intent startServiceIntent = new Intent(this, MyService.class);
PendingIntent.getService(this, requestCode,
startServiceIntent , flags);
// Broadcast an Intent
Intent broadcastIntent = new Intent(NEW_LIFEFORM_DETECTED);
PendingIntent.getBroadcast(this, requestCode,
broadcastIntent, flags);
PendingIntent 类中包含静态常量,能用来指定flag去更新或者取消任何匹配你指定的Action的已存在的Pending Intent,与去指定是否Intent只触发1次同样。
更多的细节,暂时不作讨论,之后看到Notification或者Widget的时候再说。