sendBroadcast(Intent)、sendOrderedBroadcast()、LocalBroadcastManager(進程內,更安全高效)。BroadcastReceiver,覆寫 onReceive(Context, Intent)。<intent-filter> 匹配 Action、Category、Data。在 AndroidManifest.xml 宣告,App 未啟動也能接收(如開機完成)。
在程式碼註冊/反註冊,隨元件生命週期,適合 UI 更新、臨時監聽。
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) { ... }
};
@Override protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter("com.example.CUSTOM_ACTION"));
}
@Override protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
| Action | 觸發時機 | 備註 |
|---|---|---|
android.intent.action.BOOT_COMPLETED | 開機完成 | 需 RECEIVE_BOOT_COMPLETED 權限 |
android.intent.action.ACTION_POWER_CONNECTED/DISCONNECTED | 充電器插拔 | |
android.intent.action.BATTERY_LOW/OKAY | 電量低/恢復 | |
android.intent.action.ACTION_SHUTDOWN | 關機 | 無法攔截/延遲 |
android.intent.action.TIMEZONE_CHANGED | 時區變更 | |
android.net.conn.CONNECTIVITY_CHANGE | 網路狀態變化 | Android 7.0+ 建議用 NetworkCallback |
android.intent.action.PACKAGE_ADDED/REMOVED | App 安裝/移除 | 含 android.intent.extra.PACKAGE_NAME |
Button btn = findViewById(R.id.broadcastBtn);
btn.setOnClickListener(v -> {
Intent intent = new Intent("com.example.PRINT_LOG");
intent.putExtra("info", "here is your info.");
sendBroadcast(intent);
});
public class HelloBroadReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
if ("com.example.PRINT_LOG".equals(intent.getAction())) {
Log.e("Broadcast", intent.getStringExtra("info"));
}
}
}
sendOrderedBroadcast,接收者可 abortBroadcast() 阻止傳遞、setResultData() 傳遞結果給下一個。permission,只有持有權限的 App 能收發。sendStickyBroadcast(API 21 棄用),新 App 可立即取得最後一則黏性廣播。onReceive 運行於主執行緒,嚴禁耗時操作(網路、資料庫、複雜運算),需啟動 Service 或執行緒處理。android:exported 明確聲明是否允許外部 App 發送廣播給此接收器(Android 12+ 必填)。善用廣播機制實現元件解耦、系統事件響應、跨 App 通訊。