Android消息通信之无所不能的第三方开源项目EventBus

在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发送消息进而实现通信。
先丢出本文代码:
首先要定义一个自己的Event类,这个类可以随意定义,里面包括自己想要在消息通信中传递的各种复杂数据结构,本文则简单些,MyEvent.java:

package zhangphil.service;//被EventBus类的定义可以随意//这里面可以传递更复杂、更重的数据结构public class MyEvent {public int id;public String content;@Overridepublic String toString() {return "id:" + id + " content:" + content;}}



前台Activity:

package zhangphil.service;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.widget.TextView;import de.greenrobot.event.EventBus;public class MainActivity extends Activity {private TextView text;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);text = (TextView) findViewById(R.id.textView);// 一般在onCreate方法里面注册EventBusEventBus.getDefault().register(this);startMyService();}// 这里,EventBus回调接受消息,然后更新Main UI的TextViewpublic void onEventMainThread(MyEvent event) {Log.d(this.getClass().getName(), "onEventMainThread:" + event.toString());text.setText(event + "");}// 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());}@Overrideprotected void onDestroy() {super.onDestroy();// 注销EventBusEventBus.getDefault().unregister(this);stopMyService();}private void startMyService() {Intent intent = new Intent(this, MyService.class);this.startService(intent);}private void stopMyService() {Intent intent = new Intent(this, MyService.class);this.stopService(intent);}}



后台Service:

package zhangphil.service;import android.app.IntentService;import android.content.Intent;import android.os.IBinder;import android.util.Log;import de.greenrobot.event.EventBus;public class MyService extends IntentService {public MyService() {super("MyService");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {return super.onStartCommand(intent, flags, startId);}@Overrideprotected void onHandleIntent(Intent intent) {for (int i = 0; i < 10; i++) {MyEvent event = new MyEvent();event.id = i;event.content = "数据" + i;// 可以随意在工程代码中的任意位置发送消息给订阅者EventBus.getDefault().post(event);Log.d(this.getClass().getName(), "发送消息:" + event.toString());try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}}@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onDestroy() {Log.d(this.getClass().getName(), "onDestroy");}}


说明:
(1)EventBus是消息发布者(发送消息)/订阅者(接收消息)模式。EventBus的消息发布十分灵活,可以在工程代码中的任意位置发送消息。在本例中,EventBus在Service的onHandleIntent循环发布10条消息。EventBus 发布消息只需要一行代码即可实现:
EventBus.getDefault().post(event);
Event即为自己定义的类的实例。


(2)EventBus在接收消息的Activity(或Fragment)中初始化。在本例中是一个Activity接收消息,
首先,在Activity里面注册EventBus,通常在Android的Activity(或者Fragment)的onCreate里面注册,仅需一行代码:
EventBus.getDefault().register(this);
类似于注册一个消息监听Listener,完了不要忘记注销EventBus,在onDestory里面
EventBus.getDefault().unregister(this);

(3)EventBus接收消息。
在Activity中根据代码实际情况写一个EventBus的消息接收函数:
public void onEventMainThread(MyEvent event);
然后,只要EventBus发送消息,就可以在这里接收到。


 
EventBus的消息回调接收消息函数还有几个:
onEventMainThread:Main线程,这个与Android UI线程密切相关,不要阻塞它!
onEventBackgroundThread:故名思议,后台线程中接收处理。
onEventAsync:异步线程中接收处理。


附录参考文章:
文章1:《Android Service简介(系列1)》链接地址:http://blog.csdn.net/zhangphil/article/details/49373939
文章2:《Android Activity与Service数据交互:Binder、bindService(系列2)》链接地址:http://blog.csdn.net/zhangphil/article/details/49385005
文章3:《Android Service之串行化Service:IntentService(系列3)》链接地址:http://blog.csdn.net/zhangphil/article/details/49387139
文章4:《Android Service进程间双向通信之Messenger(系列4)》http://blog.csdn.net/zhangphil/article/details/49402869
文章5:《Android进程间通信(IPC)的AIDL机制:Hello World示例 》链接地址:http://blog.csdn.net/zhangphil/article/details/43876657

更多相关文章

  1. Android 轻松实现语音识别的完整代码
  2. Android应用程序键盘(Keyboard)消息处理机制分析
  3. 10.Android之测试代码实现步骤
  4. Android客户端通过socket与服务器通信
  5. Android跨进程通信之非AIDL(二)
  6. Android消息推送实现
  7. androdi与服务器Socket通信原理

随机推荐

  1. Android软键盘弹出时布局的调整问题
  2. Android神技之 使用SVG以及自定义IconFon
  3. Material Design(六)
  4. Android中图表AChartEngine学习使用与例
  5. Android开发者的福音-良心之选
  6. Android通过WebView实现原生Java与JS交互
  7. Android(安卓)低功耗(BLE)蓝牙(三)
  8. H5跟ios、android数据对接
  9. Android--控件Button的详细用法介绍(适合
  10. 如何提交Code到google open source andro