广播接收者后续和安卓 的事件总线
粘性广播
特点:可以不用先执行注册
方法:sendstickyBroadcast
发送者
// An highlighted block
public void sendBroadCastoOther(){
Intent intent = new Intent(OtherActivity.action); //action
intent.putExtra("name","粘性广播");
sendStickyBroadcast(intent); //粘性广播
}
接收者
// An highlighted block
class SkityReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(action)){
Log.d("粘性内容",intent.getStringExtra("name")); //粘性广播
}
}
}
有序广播
步骤:
注册:多个receiver要使用一个action,设置优先级:priority
发送有序广播:sendorderedBroadcast(intent,null)
常用方法:
setResultExtras(Bundle对象)设置携带值
getResultExtras(true)获取Bundle对象
abortBroadcast():终止有序广播,不在传递下去
接收方
这样的类可以多写几个,无所谓,但是清单文件中要叫在同一个action里面。可以设置优先级
// An highlighted block
public class MyReceiver2 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("into","MyReceiver2");
if(intent.getAction().equals("myreceiver4")){
String name = intent.getStringExtra("name2");兵
Log.d("MyReceiver2Info1-name:",name+"");
Bundle bundle = new Bundle();
bundle.putString("bag1","我我我");
setResultExtras(bundle);
}
}
}
发送方
// An highlighted block
public void sendReceiver3(View view){
Intent intent = new Intent("myreceiver3");
intent.putExtra("name","我");
sendBroadcast(intent);
// sendStickyBroadcast(intent);
}
EventBus
用法:
导依赖
接收方注册:
Oncreate(){
EventBus。getDefault().register(this)
}
OnDistory(){
EventBus.getDefault.unregister(this)
}
接收方方法
@subribe(ThreadMode=ThreadMode.Mian.sticky=true)
public void receiver(object o){
o就是发送过来的值
}
发送方:
EventBus.getDefault.post(任意数据类型):普通发送
EventBus.getDefault.poststicky(任意数据类型):粘性发送