使用步驟:web
①:本身寫個消息類(須要什麼屬性就添加什麼字段)async
eg: 函數
public class MessageEvent {post
public final String message;ui
public MessageEvent(String message) {this
this.message = message;spa
}.net
}orm
②:在activity中註冊和註銷EventBus對象
EventBus.getDefault().register(this);
EventBus.getDefault().unregister(this);
③:在須要發送數據即消息的地方調用如下方法,發送你的消息類對象
EventBus.getDefault().post(new MessageEvent("fffffffffff"));
④:在須要接收數據即消息的地方,聲明並實現「訂閱函數」
@Subscribe ------------這個註解是訂閱者的標記,不可省略
/**
* MainThread: 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.
*
* @param messageEvent
*/
@Subscribe
public void onEventMainThread(MessageEvent messageEvent) {
String msg = "onEventMainThread收到了消息:" + messageEvent.message;
Log.d("harvic", msg);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
/**
* BackgroundThread: 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
*
* @param event
*/
@Subscribe
public void onEventBackgroundThread(MessageEvent event) {
Log.d("harvic", "onEventBackground收到了消息:" + event.message);
}
/**
* Async: 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
*
* @param event
*/
@Subscribe
public void onEventAsync(MessageEvent event) {
Log.d("harvic", "onEventAsync收到了消息:" + event.message);
}
/**
* PostThread: 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 should return quickly to avoid blocking the posting thread, which
* may be the main thread. Example:
*
* @param messageEvent
*/
@Subscribe
public void onEvent(MessageEvent event) {
Log.d("harvic", "OnEvent收到了消息:" + event.message);
}
所需jar包,能夠本身打,這裏我打包了一個,能夠參考