简单介绍
EventBus是一个用于简化Andorid、Fragment、Threads、Service之间信息传递的一个发布/订阅事件集。
传统的Android组件之间的通信方式有:Activity之间使用Intent;Service向Activity发送broadcast;Fragment和Activity之间相互持有对方的引用(随后可以调用对方的相关方法进行事件传递)。传统的事件传递的问题在于:通信方式没有实现解耦,是硬编码在组件中的。组件一旦发生修改,对应的通信方式就需要跟着修改。其实不管什么场景下,我们最好能够使得自己编写的代码最大限度的解耦,这是一个很好的习惯,避免无用功,提高代码利用率。
以下是两个Activity使用EventBus相互传值
依赖
implementation 'org.greenrobot:eventbus:3.1.1'
Activity
public class MainActivity extends AppCompatActivity {
@BindView(R.id.btn)
Button btn;
@BindView(R.id.text)
TextView text;
@BindView(R.id.simple)
SimpleDraweeView simple;
String urlImage = "https://img4q.duitang.com/uploads/item/201304/27/20130427043538_wAfHC.jpeg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);//绑定视图
EventBus.getDefault().register(this);//注册
}
@OnClick(R.id.btn)//点击按钮发送
public void Click() {
Message message = new Message();
message.obj = new MessageEvent("啊哈", "123456",urlImage);
EventBus.getDefault().postSticky(message);
startActivity(new Intent(MainActivity.this, EventActivity.class));
}
//粘性事件sticky = true
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void messageEvent(Bundle bundle) {
String name = bundle.getString("name");
String pwd = bundle.getString("pwd");
String url = bundle.getString("url");
text.setText("name " +name + " ==== " + "pwd " +pwd);
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setUri(Uri.parse(url))
.setAutoPlayAnimations(true)
.build();
simple.setController(controller);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);//解注册(为防止内存泄漏)
ButterKnife.bind(this).unbind();
}
}
EventActivity
public class EventActivity extends AppCompatActivity {
@BindView(R.id.btn)
Button btn;
@BindView(R.id.text)
TextView text;
@BindView(R.id.simple)
SimpleDraweeView simple;
String ss = "http://c.hiphotos.baidu.com/image/w%3D500/sign=64d9fd84bc003af34dbadc60052bc619/37d12f2eb9389b501dc8fddf8f35e5dde7116e03.jpg";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
ButterKnife.bind(this);
EventBus.getDefault().register(this);//注册
}
@OnClick(R.id.btn)
public void Click(){
Bundle bundle = new Bundle();
bundle.putString("name","呃呃呃");
bundle.putString("pwd","987654");
bundle.putString("url",ss);
EventBus.getDefault().post(bundle);
finish();
}
@Subscribe (threadMode = ThreadMode.MAIN,sticky = true)
public void messageEventBus(Message message){
MessageEvent event = (MessageEvent) message.obj;
text.setText("name "+event.name+" ==== pwd "+event.pwd);
Log.e("zmz","============"+event.urlString);
String urlString = event.urlString;
simple.setImageURI(Uri.parse(urlString));
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);//解除注册
}
}