編輯:關於 Android 開發
專案持續更新,這一期講 EventBus 的基本用法,下一篇會從源碼角度剖析它的實現過程。
FastDev4Android 框架地址:https://github.com/jiangqqlmj/FastDev4Android
以前做組件間的消息分發,通常是觀察者模式或者接口回調。這些做法能解決問題,但代價是組件之間耦合嚴重,程式碼可讀性和可維護性都變差。
EventBus 是一款針對 Android 優化的發布/訂閱事件總線,主要用來替代 Intent、Handler、BroadCast 在 Fragment、Activity、Service 與線程之間傳遞消息。它的優點是開銷小、寫法優雅,並把發送者與接收者彻底解耦。
開源地址:https://github.com/greenrobot/EventBus

它的特點可以歸納為:
3.1 Gradle 配置
compile 'de.greenrobot:eventbus:2.4.0'
3.2 定義事件對象——一個普通 POJO 即可,不需要繼承任何類:
public class MessageEvent {
/* Additional fields if needed */
}
3.3 在接收方註冊
eventBus.register(this);
3.4 撰寫接收方法——方法名以 onEvent 開頭,參數類型即為事件類型:
public void onEvent(AnyEventType event) {
/* Do something */
}
3.5 發送消息
eventBus.post(event);
4.1 需求:第一個 Activity 有一個按鈕和一個 TextView。點擊按鈕打開第二個 Activity;在第二個 Activity 點擊按鈕關閉自己,同時把消息回傳給第一個 Activity 顯示在 TextView 上。
用傳統寫法,這需要 startActivityForResult + onActivityResult 一整套流程;用 EventBus,只需一次 post。

4.2 兩個布局
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="點擊打開第二個 Activity" />
<TextView
android:id="@+id/textView_one"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="這邊顯示消息內容..." />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第二個 Activity 的按鈕" />
<TextView
android:id="@+id/textView_two"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:text="當前為第二個 Activity" />
</LinearLayout>
4.3 定義事件類——把要傳遞的資料封裝在裡面:
package com.chinaztt.fda.event;
/**
* EventBus 測試用事件類
*/
public class TestEventFirst {
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public TestEventFirst(String msg) {
this.msg = msg;
}
}
4.4 註冊與反註冊
// 註冊
EventBus.getDefault().register(this);
// 反註冊,必須成对出現,否則會內存洩漏
EventBus.getDefault().unregister(this);
4.5 發送消息
EventBus.getDefault().post(new TestEventFirst("我是第二個 Activity 回傳的信息...."));
4.6 接收消息——在已註冊的 Activity 中重寫 onEventMainThread(),它保證回調發生在主線程,可以直接更新 UI:
/**
* 收到消息後的處理
*/
public void onEventMainThread(TestEventFirst event) {
textView_one.setText(event.getMsg());
showToastMsgShort(event.getMsg());
}
方法參數的類型就是事件類型,所有資料都封裝在 event 對象裡,取出使用即可。(除此之外 EventBus 還有另外三個回調方法,下一篇再細說。)
4.7 兩個 Activity 的完整程式碼
package com.chinaztt.fda.test;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.chinaztt.fda.event.TestEventFirst;
import com.chinaztt.fda.ui.R;
import com.chinaztt.fda.ui.base.BaseActivity;
import org.androidannotations.annotations.EActivity;
import de.greenrobot.event.EventBus;
/**
* EventBus 組件間數據通信示例
*/
@EActivity
public class EventBusTestActivity extends BaseActivity {
Button button_one;
TextView textView_one;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_bus_test_layout);
EventBus.getDefault().register(this);
button_one = (Button) this.findViewById(R.id.button_one);
textView_one = (TextView) this.findViewById(R.id.textView_one);
button_one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openActivity(EventBusTestTwoActivity_.class);
}
});
}
/**
* 收到消息後更新界面
*/
public void onEventMainThread(TestEventFirst event) {
textView_one.setText(event.getMsg());
showToastMsgShort(event.getMsg());
}
@Override
protected void onDestroy() {
super.onDestroy();
// 務必反註冊
EventBus.getDefault().unregister(this);
}
}
package com.chinaztt.fda.test;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.chinaztt.fda.event.TestEventFirst;
import com.chinaztt.fda.ui.R;
import com.chinaztt.fda.ui.base.BaseActivity;
import org.androidannotations.annotations.EActivity;
import de.greenrobot.event.EventBus;
@EActivity
public class EventBusTestTwoActivity extends BaseActivity {
Button button_two;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_bus_test_two_layout);
button_two = (Button) this.findViewById(R.id.button_two);
button_two.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().post(
new TestEventFirst("我是第二個 Activity 回傳的信息...."));
EventBusTestTwoActivity.this.finish();
}
});
}
}
這裡最容易踩的坑只有一個:register 與 unregister 必須成对,否則 Activity 被銷毀後仍被總線持有,內存洩漏與「更新已死界面」的怪異 bug 都會跟著來。EventBus 的基本用法到此結束,更深入的解析與其他回調方法留待下一篇。
用 PinnedSectionListView 打造分組懸浮的通訊錄頁面
延伸閱讀:PinnedSectionListView 的下載、用法與注意事項:https://www.cnblogs.com/zzw1994/p/4997601.html
使用 adb pull / push 在手機與電腦間傳輸檔案與資料庫
使用 adb pull / push 在手機與電腦間傳輸檔案與資料庫 先來談談 adb 命令的環境設定。如果你遇到「adb 不是內部或外部命令」的提示,通常是因為尚未設定
AngularJS 實戰疑難:修正重新整理後 $stateParams 導致的畫面異常
俗話說細節決定成敗,編程更是如此。有些問題平時不出現,卻在特定的操作路徑上突然爆發——重新整理就是最典型的一個。 問題現象 頁面正常載入時,顯示完全正常: 但按下 F
Android 博客園客戶端實作:查看評論與搜尋博主
Android 博客園客戶端實作:查看評論與搜尋博主 本系列以博客園為例,示範如何打造 Android 客戶端。這一篇聚焦在兩個常見功能:查看文章或新聞評論,以及搜尋博主