在Android开发中,消息通信在开发过程中是比较重要但比较略微繁琐的过程,比如,Activity与Fragment之间的消息通信,后台Service与前台Activity的消息通信,Fragment与Fragment之间的消息通信等等情况,Android本身提供的有完善的广播、在Service中也有的Messenger、handler中处理message等等完备的解决方案,而第三方的开源库EventBus同样提供了几乎无所不能、易于理解和使用的Android消息事件解决方案。
EventBus是github上的一个第三方开发库,其在github上的项目主页地址:https://github.com/greenrobot/EventBus
EventBus的消息模型是消息发布者/订阅者机制。
使用EventBus之前需要到EventBus项目主页上将库项目(https://github.com/greenrobot/EventBus/tree/master/EventBus ,截止2015年10月26日更新时间,未来也许有变动)包拖下来,接着作为Eclipse的一个工程导入,然后作为Android的一个lib,在自己的项目中引用即可。
本文以一个简单的代码例子说明EventBus。附录参考文章2、3、4说明了如何实现前台Activity与后台Service之间的消息通信,本文则在附录参考文章4的基础上改造,使用EventBus实现后台Service往前台Activity发送消息进而实现通信。
第一步:导入EventBus
第二步:勾选Is Library
第三步:所需项目导入EventBus包
创建一个类
public class MyEvent {
public int id;
public String content;
@Override
public String toString(){
return content;
}
}
public class MainActivity extends Activity {
// private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// text = (TextView) findViewById(R.id.text);
// EventBus.getDefault().register(this);
task();
Intent intent = new Intent(this, MyAppService.class);
startService(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent(this, MyAppService.class);
stopService(intent);
}
private void task() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
MyEvent event = new MyEvent();
event.id = i;
event.content = "hello,world !" + i;
EventBus.getDefault().post(event);// post抛出消息
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
MyService中
public class MyAppService extends Service {
// 仅仅create一次
@Override
public void onCreate() {
EventBus.getDefault().register(this);// 接收消息
}
@Override
public void onDestroy() {
EventBus.getDefault().unregister(this);// 停止接收消息
}
// 这里,EventBus回调接受消息,然后更新Main UI的TextView
public void onEventMainThread(MyEvent event) {
Log.d(this.getClass().getName(), "onEventMainThread:" + event.toString());
}
// EventBus回调接受消息
public void onEventBackgroundThread(MyEvent event) {
Log.d(this.getClass().getName(), "onEventBackgroundThread:" + event.toString());
}
// EventBus回调接受消息
public void onEventAsync(MyEvent event) {
Log.d(this.getClass().getName(), "onEventAsync:" + event.toString());
}
}