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

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

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

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

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

最后在onstop()反注册;.net

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

EventBus的ThreadMode

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

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. }  
相关文章
相关标签/搜索