作為一枚Android開(kāi)發(fā)者,關(guān)于EventBus相信應(yīng)該都聽(tīng)說(shuō)過(guò)。要是用過(guò)就請(qǐng)忽略本文,本文講得比較基礎(chǔ)。
要是沒(méi)用過(guò),建議你花兩分鐘看看。
目前EventBus最新版本是3.0,本demo基于3.0編寫(xiě)的。
GitHub : https://github.com/greenrobot/EventBus
官方文檔:http://greenrobot.org/eventbus/documentation
一、EventBus概述
EventBus是一個(gè)Android端優(yōu)化的publish/subscribe消息總線,簡(jiǎn)化了應(yīng)用程序內(nèi)各組件間、組件與后臺(tái)線程間的通信。
作為一個(gè)消息總線主要有三個(gè)組成部分:
- 事件(Event)
- 事件訂閱者(Subscriber)
-
事件發(fā)布者(Publisher)
官方提供的關(guān)系圖
二、EventBus用法
1、把EventBus依賴到項(xiàng)目
build.gradle添加引用
compile 'org.greenrobot:eventbus:3.0.0'
Maven
<dependency>
<groupId>org.greenrobot</groupId>
<artifactId>eventbus</artifactId>
<version>3.0.0</version>
</dependency>
或者直接下載EventBus 架包jar 放到項(xiàng)目中
2、構(gòu)造發(fā)送消息類,也就是發(fā)送的對(duì)象
public class MainMessage{
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
3、注冊(cè)/解除注冊(cè)
EventBus.getDefault().register(this);//注冊(cè)
EventBus.getDefault().unregister(this);//解除注冊(cè)
4 、發(fā)送消息
EventBus.getDefault().post(new MainMessage("你好,愛(ài)開(kāi)發(fā)");
ThreadMode總共四個(gè):
MAIN UI主線程
POSTING 默認(rèn)調(diào)用方式,在調(diào)用post方法的線程執(zhí)行,避免了線程切換,性能開(kāi)銷最少
BACKGROUND 如果調(diào)用post方法的線程不是主線程,則直接在該線程執(zhí)行。
如果是主線程,則切換到后臺(tái)單例線程,多個(gè)方法公用同個(gè)后臺(tái)線程,按順序執(zhí)行,避免耗時(shí)操作ASYNC 開(kāi)辟新獨(dú)立線程,用來(lái)執(zhí)行耗時(shí)操作,例如網(wǎng)絡(luò)訪問(wèn)。
來(lái)看一下源碼,ThreadMode也就一個(gè)枚舉,英文自己對(duì)照理解吧,不是很復(fù)雜
public enum 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
}
5 、事件處理
//ui主線程中執(zhí)行
@Subscribe(threadMode = ThreadMode.Main)
public void onMainEventBus(MainMessage msg) {
}
6、priority事件優(yōu)先級(jí)
//priority越大,級(jí)別越高
@Subscribe(threadMode = ThreadMode.MAIN,priority = 100)
public void onEvent(MainMessage event) {
}
7、終止事件傳遞
// 注意中止事件傳遞,后續(xù)事件不在調(diào)用
@Subscribe
public void onEvent(MessageEvent event){
EventBus.getDefault().cancelEventDelivery(event) ;
}
下面我們來(lái)看一個(gè)完整的demo
先看一下效果圖:

新建兩個(gè)activity,分別為MainActivity和 SecondActivity
其中MainActivity來(lái)放了五個(gè)按鈕和一個(gè)文本框
SecondActivity只有一個(gè)按鈕,點(diǎn)擊按鈕通知MainActivity頁(yè)面更新。
看一下MainActivity主要代碼:
/**
* 主線程中執(zhí)行
*
* @param msg
*/
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMainEventBus(MainMessage msg) {
Log.e(TAG, msg.getMessage());
tv_desc.setText(msg.getMessage());
}
/**
* 后臺(tái)線程
*
* @param msg
*/
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onBackgroundEventBus(BackgroundMessage msg) {
Log.e(TAG, msg.getMessage());
}
/**
* 異步線程
*
* @param msg
*/
@Subscribe(threadMode = ThreadMode.ASYNC)
public void onAsyncEventBus(AsyncMessage msg) {
Log.e(TAG, msg.getMessage());
}
/**
* 默認(rèn)情況,和發(fā)送事件在同一個(gè)線程
*
* @param msg
*/
@Subscribe(threadMode = ThreadMode.POSTING)
public void onPostEventBus(PostingMessage msg) {
Log.e(TAG, msg.getMessage());
}
按鈕點(diǎn)擊事件
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnMain:
EventBus.getDefault().post(new MainMessage("MainMessage"));
break;
case R.id.btnBackground:
EventBus.getDefault().post(new BackgroundMessage("BackgroundMessage"));
break;
case R.id.btnAsync:
EventBus.getDefault().post(new AsyncMessage("AsyncMessage"));
break;
case R.id.btnPosting:
EventBus.getDefault().post(new PostingMessage("PostingMessage"));
break;
case R.id.btn1:
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
break;
}
}
分別點(diǎn)擊前面四個(gè)按鈕時(shí)控制臺(tái)按順序輸出:

SecondActivity頁(yè)面點(diǎn)擊發(fā)送消息的事件
EventBus.getDefault().post(new MainMessage("傳遞信息:aikaifa"));
在MianActivity頁(yè)面我們就能接受到SecondActivity傳遞過(guò)來(lái)的信息了。
如果感興趣想跑一下項(xiàng)目,源碼請(qǐng)戳這里
[END]
我是洪生鵬,
熱衷旅行、寫(xiě)作,目前過(guò)著白天到工地搬磚、晚上寫(xiě)故事的生活。
希望今天的文章對(duì)你有幫助。
堅(jiān)持日更,一般會(huì)在晚上10點(diǎn)發(fā)文,歡迎交流。
優(yōu)質(zhì)文章推薦:
