1. 比较
性能 对比 : EventBus不差
EventBus ~ LocalBroadCast > Bradocast
运行的线程环境: EventBus完胜!
LocalBroadcastManager 所有调用都是在主线程,
EventBus 可以定义在调用线程、主线程、后台线程、异步。代码量比较: EventBus完胜!
Bradocast
@Override public void onStart() { super.onStart(); // 注册广播接收 IntentFilter filter = new IntentFilter(); filter.addAction(Constants.USER_UPDATE); receiveBroadCast = new ReceiveBroadCast(); registerReceiver(receiveBroadCast, filter); } // 发送 Intent intent = new Intent(); intent.setAction(Constants.BP_UPDATE); sendBroadcast(intent); class ReceiveBroadCast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if ( !TextUtils.isEmpty(action) && action.equals(Constants.USER_UPDATE)) { Bundle bundle = intent.getExtras(); if (null != bundle) { ...do Something } } } } } @Override public void onStop() { super.onStop(); if (receiveBroadCast != null) { unregisterReceiver(receiveBroadCast);//注销 } }
EventBus
EventBus.getDefault().register(this);//注册 EventBus.getInstance().post(ourEvnet()); //发送 @Subscribe public void onEvent(TokenInvalidEvent event) { .....处理接收到的消息 } EventBus.getDefault().unregister(this); //注销
LocalBroadcastManager
//注册 LocalBroadcastReceiver localReceiver = new LocalBroadcastReceiver(); LocalBroadcastManager.getInstance(context).registerReceiver(localReceiver, new IntentFilter(ACTION_LOCAL_SEND)); //发送 LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(ACTION_LOCAL_SEND)); //接收广播 public class LocalBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { localMsg.setText(intent.getStringExtra(MSG_KEY)); } } //取消 LocalBroadcastManager.getInstance(context).unregisterReceiver(localReceiver);
好啦,我们可以看到,如果追求代码行数,正常人都会选择用
EventBus
,简单好用!
EventBus < BroadCast ~ LocalBroadCast 。
信息量
- 系统广播: