Android为TV端助力 EventBus.getDefault()开源框架

在onCreate里面执行 EventBus.getDefault().register(this);意思是让EventBus扫描当前类,把所有onEvent开头的方法记录下来,如何记录呢?使用Map,Key为方法的参数类型,Value中包含我们的方法。

这样在onCreate执行完成以后,我们的onEventMainThread就已经以键值对的方式被存储到EventBus中了。

然后当子线程执行完毕,调用EventBus.getDefault().post(new ItemListEvent(Item.ITEMS))时,EventBus会根据post中实参的类型,去Map中查找对于的方法,于是找到了我们的onEventMainThread,最终调用反射去执行我们的方法。

现在应该明白了,整个运行的流程了;那么没有接口却能发生回调应该也能解释了。

最后在onstop()反注册;

转载在鸿洋哥,感谢他!附上他的博客地址 http://blog.csdn.net/lmj623565791/article/details/40794879

EventBus的ThreadMode

EventBus包含4个ThreadMode:PostThread,MainThread,BackgroundThread,Async

MainThread我们已经不陌生了;我们已经使用过。

具体的用法,极其简单,方法名为:onEventPostThread, onEventMainThread,onEventBackgroundThread,onEventAsync即可

具体什么区别呢?

onEventMainThread代表这个方法会在UI线程执行

onEventPostThread代表这个方法会在当前发布事件的线程执行

BackgroundThread这个方法,如果在非UI线程发布的事件,则直接执行,和发布在同一个线程中。如果在UI线程发布的事件,则加入后台任务队列,使用线程池一个接一个调用。

Async 加入后台任务队列,使用线程池调用,注意没有BackgroundThread中的一个接一个。

如图

  1. public class SampleComponent extends Fragment  
  2. {  
  3.   
  4.     @Override  
  5.     public void onCreate(Bundle savedInstanceState)  
  6.     {  
  7.         super.onCreate(savedInstanceState);  
  8.         EventBus.getDefault().register(this);  
  9.     }  
  10.   
  11.     public void onEventMainThread(param)  
  12.     {  
  13.     }  
  14.       
  15.     public void onEventPostThread(param)  
  16.     {  
  17.           
  18.     }  
  19.       
  20.     public void onEventBackgroundThread(param)  
  21.     {  
  22.           
  23.     }  
  24.       
  25.     public void onEventAsync(param)  
  26.     {  
  27.           
  28.     }  
  29.       
  30.     @Override  
  31.     public void onDestroy()  
  32.     {  
  33.         super.onDestroy();  
  34.         EventBus.getDefault().unregister(this);  
  35.     }  
  36.       
  37. }  
posted @ 2017-02-23 19:11  水柠檬QAQ  阅读(1883)  评论(0编辑  收藏  举报