Android学习系列(43)--使用事件总线框架EventBus和Otto

十度 Android 2015年12月01日 收藏

事件总线框架

针对事件提供统一订阅,发布以达到组件间通信的解决方案。

原理

观察者模式。

EventBus和Otto

先看EventBus的官方定义:

  1. Android optimized event bus that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.

再看Otto官方定义:

  1. Otto is an event bus designed to decouple different parts of your application while still allowing them to communicate efficiently.

总之,简化android应用内组件通信。

对比BroadcastReceiver

在工作上,我在两个场景下分别使用过Otto和EventBus,一个是下载管理器通知各个相关的Activity当前的进度,一个是设置应用壁纸。
单从使用上看,EventBus > Otto > BroadcastReceiver(当然BroadcastReceiver作为系统内置组件,有一些前两者没有的功能).
EventBus最简洁,Otto最符合Guava EventBus的设计思路, BroadcastReceiver最难使用。
我个人的第一选择是EventBus。

实例:“设置壁纸”

两大的框架的基本使用都非常简单:
EventBus的基本使用官方参考:https://github.com/greenrobot/EventBus
Otto的基本使用官方参考:http://square.github.io/otto/

EventBus实现篇

EventBus规定onEvent方法固定作为订阅者接受事件的方法,应该是参考了“约定优于配置”思想。

  1. 定义EventModel,作为组件间通信传递数据的载体

    1. public class WallpaperEvent {
    2. private Drawable wallpaper;
    3. public WallpaperEvent(Drawable wallpaper) {
    4. this.wallpaper = wallpaper;
    5. }
    6. public Drawable getWallpaper() {
    7. return wallpaper;
    8. }
    9. public void setWallpaper(Drawable wallpaper) {
    10. this.wallpaper = wallpaper;
    11. }
    12. }
  2. 定义订阅者,最重要的是onEvent方法

    1. public class BaseActivity extends Activity {
    2. @Override
    3. protected void onCreate(Bundle savedInstanceState) {
    4. super.onCreate(savedInstanceState);
    5. EventBus.getDefault().register(this);
    6. initWallpaper();
    7. }
    8. @Override
    9. protected void onDestroy() {
    10. super.onDestroy();
    11. EventBus.getDefault().unregister(this);
    12. }
    13. public void onEvent(WallpaperEvent wallpaperEvent) {
    14. // AppConfig.sWallpaperDrawable as a global static var
    15. AppConfig.sWallpaperDrawable = wallpaperEvent.getWallpaper();
    16. initWallpaper();
    17. }
    18. private void initWallpaper() {
    19. // support custom setting the wallpaper
    20. // 根据AppConfig.sWallpaperDrawable,默认值等设置当前Activity的背景壁纸
    21. // ...
    22. }
    23. }
  3. 通过post()方法在任何地方发布消息(壁纸,准确的说是WallpaperEvent)给所有的BaseActivity子类,举个例子:

    1. private void downloadWallpapper(String src) {
    2. ImageLoader.getInstance().loadImage(src, new SimpleImageLoadingListener() {
    3. @Override
    4. public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
    5. BitmapDrawable wallpaper = new BitmapDrawable(loadedImage);
    6. // presist the image url for cache
    7. saveWallpaper(imageUri);
    8. // notify all base activity to update wallpaper
    9. EventBus.getDefault().post(new WallpaperEvent(wallpaper));
    10. Toast.makeText(WallpapeEventBusrActivity.this,
    11. R.string.download_wallpaper_success,
    12. Toast.LENGTH_SHORT).show();
    13. }
    14. @Override
    15. public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
    16. Toast.makeText(WallpaperActivity.this,
    17. R.string.download_wallpaper_fail,
    18. Toast.LENGTH_SHORT).show();
    19. }
    20. });
    21. }

    重点就是这句:

    1. // 在任何地方调用下面的方法,即可动态全局实现壁纸设置功能
    2. EventBus.getDefault().post(new WallpaperEvent(wallpaper));

Otto实现篇

这里要注意几点点:
(1)Otto使用注解定义订阅/发布者的角色,@Subscribe为订阅者,@Produce为发布者,方法名称就可以自定义了。
(2)Otto为了性能,代码意图清晰,@Subscribe,@Produce方法必须定义在直接的作用类上,而不能定义在基类而被继承。
(3)和EventBus不同的是,发布者也需要register和unregister,而EventBus的发布者是不需要的。

  1. 定义EventModel,作为组件间通信传递数据的载体

    1. public class WallpaperEvent {
    2. private Drawable wallpaper;
    3. public WallpaperEvent(Drawable wallpaper) {
    4. this.wallpaper = wallpaper;
    5. }
    6. public Drawable getWallpaper() {
    7. return wallpaper;
    8. }
    9. public void setWallpaper(Drawable wallpaper) {
    10. this.wallpaper = wallpaper;
    11. }
    12. }
  2. 避免浪费,相对于EventBus.getDefault(), Otto需要自己实现单例。

    1. public class AppConfig {
    2. private static final Bus BUS = new Bus();
    3. public static Bus getInstance() {
    4. return BUS;
    5. }
    6. }
  3. 定义订阅者,在接受事件的方法加上修饰符@Subscribe

    1. public class BaseActivity extends Activity {
    2. @Override
    3. protected void onCreate(Bundle savedInstanceState) {
    4. super.onCreate(savedInstanceState);
    5. AppConfig.getBusInstance().register(this);
    6. initWallpaper();
    7. }
    8. @Override
    9. protected void onDestroy() {
    10. super.onDestroy();
    11. AppConfig.getBusInstance().unregister(this);
    12. }
    13. public void onOttoEvent(WallpaperEvent wallpaperEvent) {
    14. AppConfig.sWallpaperDrawable = wallpaperEvent.getWallpaper();
    15. initWallpaper();
    16. }
    17. private void initWallpaper() {
    18. // support custom setting the wallpaper
    19. // 根据AppConfig.sWallpaperDrawable,默认值等设置当前Activity的背景壁纸
    20. // ...
    21. }
    22. }
  4. 定义发布者,通过post()方法在任何地方发布消息了

    1. public class WallpaperActivity extends BaseActivity {
    2. private Drawable wallpaperDrawable;
    3. //这里同时也要更新自己壁纸,所以显示定义@Subscribe的方法
    4. @Subscribe
    5. public void onWallpaperUpdate(WallpaperEvent wallpaperEvent) {
    6. super.onWallpaperUpdate(wallpaperEvent);
    7. }
    8. @Produce
    9. public WallpaperEvent publishWallPaper() {
    10. return new WallpaperEvent(wallpaperDrawable);
    11. }
    12. private void downloadWallpapper(String src) {
    13. //...
    14. //通知所有@Subscribe匹配WallpaperEvent参数的方法执行
    15. AppConfig.getBusInstance().post(publishWallPaper());
    16. //...
    17. }
    18. }

小结

  1. 使用设计模式的思想解决问题,这才是设计模式的真正价值。
  2. 这两个android事件总线框架提供了一种更灵活更强大而又更加完美解耦的解决方案,在很多场合,从开发效率,执行性能和设计思路上都要优于BroadcastReceiver,值得学习使用。