BroadCastReceiver有序广播和EventBus

BroadCastReceiver有序广播和EventBus

有序广播

步骤:
注册()多个receiver要使用同一个action) priority来指定优先级
发送有序广播 sendOrderedBroadcast(intent,null);
常用方法
setResultExtras(Bundle对象)设置携带数据
getResultExtras(true) 获取携带数据得到的是bundle对象
abortBroadCast() 终止有序广播

粘性广播

特点:可以不用先执行注册方(延时首广播)
方法:sendStickyBroadCast(intent对象);

代码片段

粘性广播发送方
两个方法

public void nianxing(){
		//参数为action
        Intent intent = new Intent("888");
        intent.putExtra("name","粘性广播");
        sendStickyBroadcast(intent);
    }

    public void other(){
    //在这里创建线程
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                //粘性延迟5秒钟
                    Thread.sleep(5000);
                    Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                    startActivity(intent);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

接收方注册

public class Main2Activity extends AppCompatActivity {

    Myreceiver myreceiver = new Myreceiver();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
		//注册
        IntentFilter intentFilter = new IntentFilter("888");
        registerReceiver(myreceiver,intentFilter);
    }
	//继承接受消息
    class Myreceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("888")){
                String name = intent.getStringExtra("name");
                Log.e("###粘性广播",name);
            }
        }
    }
	//关闭方法
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myreceiver);
    }
}

EventBus

EventBus:安卓的事件总线(传递数据)
用法:
1.导依赖
2.接收方注册
onCreate(){EventBus.getDefault().register(this);}
onDistory(){EventBus.getDefault().unregister(this);}
接收方法 @Subscribe(threadMode = ThreadMode.Main,sticky=true)
public void receive(Object o){o就是你发过来的值}
3.发送方
EventBus.getDefault().post(任意类型内容);
EventBus.getDefault().postSticky(任意类型内容);//粘性发送

上一篇:献给android原生应用层开发初学者技术架构选型和整合的方案思路(五)


下一篇:andorid jar/库源码解析 EventBus