編輯:關於 Android 程式設計
做過 Android 開發,遲早都會碰到 EventBus。這是一個針對 Android 最佳化的發布/訂閱事件總線,主要用來取代 Intent、Handler、BroadCast 在 Fragment、Activity、Service 與執行緒之間傳遞訊息。它的優點是開銷小、程式碼更乾淨,而且能把「發送者」與「接收者」徹底解耦——發送方不需要知道誰在聽,接收方也不需要知道訊息從哪來。
事件本身就是一個普通的 POJO,不需要繼承任何基底類別:
package com.example.eventbusdemo;
/**
* 事件消息實體類
*/
public class MainSendEvent {
protected String mstrMsg;
public MainSendEvent(String msg) {
mstrMsg = msg;
}
public String getStringMsgData() {
return mstrMsg;
}
}
package com.example.eventbusdemo;
import de.greenrobot.event.EventBus;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 事件註冊
EventBus.getDefault().register(this);
InitUI();
}
private void InitUI() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Intent intent = new Intent();
intent.setClass(MainActivity.this, TwoActivity.class);
startActivity(intent);
break;
default:
break;
}
}
// 事件接收:方法名以 onEventMainThread 開頭,表示在主執行緒回呼
public void onEventMainThread(MainSendEvent event) {
if (event != null) {
Toast.makeText(getApplicationContext(),
"MainActivity 接受數據 " + event.getStringMsgData(),
Toast.LENGTH_LONG).show();
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText(event.getStringMsgData());
}
}
@Override
public void onDestroy() {
// 取消註冊,避免記憶體洩漏
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}
package com.example.eventbusdemo;
import de.greenrobot.event.EventBus;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* TwoActivity 負責發送事件
*/
public class TwoActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
// 事件發送
EventBus.getDefault().post(new MainSendEvent("from TwoActivity msg"));
break;
default:
break;
}
}
}
activity_main.xml:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="第二個 activity" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
activity_two.xml:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="MainActivity" />
</LinearLayout>
整體流程是:進入 MainActivity → 點按鈕跳到 TwoActivity → 在 TwoActivity 點按鈕發送事件 → MainActivity 收到後用 Toast 提示並 setText,返回後就能看到文字已更新。

1. 註冊/訂閱
EventBus.getDefault().register(this);
2. 撰寫接收方法
public void onEventMainThread(MainSendEvent event) {
if (event != null) {
Toast.makeText(getApplicationContext(),
"MainActivity 接受數據 " + event.getStringMsgData(),
Toast.LENGTH_LONG).show();
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText(event.getStringMsgData());
}
}
3. 取消註冊
EventBus.getDefault().unregister(this);
前兩步與第三步都在同一個頁面完成,第四步則由發送方執行:
EventBus.getDefault().post(new MainSendEvent("from TwoActivity msg"));
一定要在 onDestroy 中 unregister。這是新手最常犯的錯誤,忘記取消註冊會導致 Activity 被 EventBus 持有的 listener 引用而無法回收,也就是記憶體洩漏。
方法命名決定執行緒。EventBus 3.x 改用 @Subscribe(threadMode = ...) 註解,而上面示範的 2.x 則靠方法名前綴辨識:onEventMainThread 在主執行緒、onEventBackgroundThread 在背景執行緒、onEvent 則在發送時所在的執行緒。若要在背景執行緒更新 UI 之外處理耗時工作,選錯 threadMode 是常見效能問題的來源。
别把它當成資料快取。EventBus 是「一次性事件」,沒有接收方時訊息就直接丟掉了。需要持久保存的狀態應該放在 ViewModel、Repository 或資料庫裡,事件只用來通知「有東西變了」。
Android RecyclerView 入門:從 ViewHolder 到自訂點擊事件
RecyclerView 到底是什麼 把它理解成 ListView 的進化版最省事。ListView 之所以卡,是因為 item 大量重建;解法是 ViewHolder—
Android Fragment 靜態加載完整示例
一、Fragment 知識概要 Android 3.0 引入了 Fragment,主要目的是適配大屏幕設備,支持更動態、更靈活的 UI 設計。Fragment 應當被視為
Android 入門:建立簡單表單與按鈕事件
本文以一個簡單的 Android 範例說明如何建立基本表單,包括文字輸入框、標籤與按鈕,並透過 Java 程式碼取得輸入內容、綁定點擊事件與顯示 Toast 訊息。在布局
Android 資料儲存(三):SQLite 資料庫儲存完整指南
SQLite 是 Android 系統內建的資料庫,屬於輕量級關聯式資料庫。它運算速度快、佔用資源少,非常適合行動裝置;不僅支援標準 SQL 語法,也遵循資料庫的 ACI