EventBus的使用

一年多前就出现来这个技术,但是也没有怎么去了解和使用,一直以为EventBus和广播类似呢,后来才发现,EventBus更好用,类型更明确,发送的消息可以是任何自定义的对象,因此写个简单的使用,以免忘记

Github项目框架的地址:https://github.com/greenrobot/EventBus

使用步骤:

一、创建消息类(实体),用于存放消息的内容,例如:

1
2
3
4
5
6
7
8
9
10
class EventMessage{
String messge;
public void setMessge(String message){
this.message=message;
}
public String getMessage(){
return message;
}

}

二、注册消息:

EventBus.getDefault().register(this);

三、接受消息:

1
2
3
4
5
@Subscribe(threadMode = ThreadMode.MAIN)
public void showEventBuss(EventMessage event) {
String msg = "收到了消息:" + event.getMessage();
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}

其中方法名无所谓,内部运用了反射的机制,获取到方法名,进行的调用,ThreadMode有四种:
/**

  • Subscriber will be called in the same thread, which is posting the event. This is the default. Event delivery
  • implies the least overhead because it avoids thread switching completely. Thus this is the recommended mode for
  • simple tasks that are known to complete is a very short time without requiring the main thread. Event handlers
  • using this mode must return quickly to avoid blocking the posting thread, which may be the main thread.
    */
    POSTING,

/**

  • Subscriber will be called in Android’s main thread (sometimes referred to as UI thread). If the posting thread is
  • the main thread, event handler methods will be called directly. Event handlers using this mode must return
  • quickly to avoid blocking the main thread.
    */
    MAIN,在主线程中调用执行

/**

  • Subscriber will be called in a background thread. If posting thread is not the main thread, event handler methods
  • will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single
  • background thread, that will deliver all its events sequentially. Event handlers using this mode should try to
  • return quickly to avoid blocking the background thread.
    */
    BACKGROUND,在子线程中执行

/**

  • Event handler methods are called in a separate thread. This is always independent from the posting thread and the
  • main thread. Posting events never wait for event handler methods using this mode. Event handler methods should
  • use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number
  • of long running asynchronous handler methods at the same time to limit the number of concurrent threads. EventBus
  • uses a thread pool to efficiently reuse threads from completed asynchronous event handler notifications.
    */
    ASYNC

四、注销消息:

EventBus.getDefalt().unregister(this);

分享到 评论