Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 四大組件入門:廣播接收器與 Service 的實際用法

編輯:關於 Android 程式設計

前言:在 Android 四大組件裡,廣播(Broadcast)與服務(Service)堪稱最「低調」的兩個。使用者幾乎感覺不到它們的存在,但它們的身影其實無處不在——簡訊收發、狀態列通知、夜間模式、背景音樂播放,背後都有它們在運作。本文先談廣播,再談服務,並附上可以跑起來的實作範例。

One:廣播 BroadcastReceiver

1. 基本認知

  • 類別名稱:BroadcastReceiver
  • 職責:監聽系統或應用發出的全域廣播訊息,作為組件之間解耦溝通的通道。
  • 常見場景:飛行模式、後台音樂(搭配 Service)、電量變化、簡訊收發、電源接離、APK 裝卸、記憶體狀態、拍照、開機自啟等。

2. 最基礎的用法

流程只有兩步:先建立 Intent 並設定 Action,再呼叫 sendBroadcast() 或 sendOrderedBroadcast() 發送。

Intent intent = new Intent();
// 這裡使用自訂 Action,記得在 Manifest 中註冊對應的 filter
intent.setAction("com.maiyu.action.MAIYU_BROADCAST");
intent.putExtra("msg", "自定義的廣播");
sendBroadcast(intent);

接著自訂接收器,繼承 BroadcastReceiver 並覆寫 onReceive:

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,
                "接收到的 Action 為:" + intent.getAction()
                        + "\n訊息內容是:" + intent.getStringExtra("msg"),
                Toast.LENGTH_SHORT).show();
    }
}

最後別忘了在 AndroidManifest.xml 中註冊:

<receiver android:name=".MyReceiver">
    <intent-filter>
        <action android:name="com.maiyu.action.MAIYU_BROADCAST" />
    </intent-filter>
</receiver>

3. 兩種廣播的區別

類型發送方法特性
普通廣播 Normal BroadcastsendBroadcast()所有接收器同時收到,無法傳遞處理結果,也無法中斷傳播
有序廣播 Ordered BroadcastsendOrderedBroadcast()依優先級(IntentFilter.setPriority)由高到低依序傳遞;優先級不足者收不到,高優先級接收後可以選擇中止後續傳播

4. 更實務的寫法:動態註冊

除了靜態宣告,另一種常見做法是在程式碼中用 registerReceiver() 動態註冊,優點是可以隨時開關監聽。以「開機自啟」為例:

class BootCompleteReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // 開機完成是系統 action
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            Intent newIntent = new Intent(context, FourActivity.class);
            newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(newIntent);
        }
    }
}
// 建立接收器
BCreceiver = new BootCompleteReceiver();

// 需要監聽時註冊(三行程式碼可壓縮為一行)
IntentFilter inf = new IntentFilter();
inf.addAction(Intent.ACTION_BOOT_COMPLETED);
registerReceiver(BCreceiver, inf);

// 不再需要時解除註冊
if (BCreceiver != null) {
    unregisterReceiver(BCreceiver);
}

動態註冊時,記得在 Manifest 加上權限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

由此可見 registerReceiver() 接收兩個參數:自訂的接收器物件,以及 IntentFilter 物件;而 unregisterReceiver() 只需要傳入接收器物件。

5. 常用系統 Action 速查

場景Action
拍照鍵按下Intent.ACTION_CAMERA_BUTTON
耳機插入Intent.ACTION_HEADSET_PLUG
電量過低Intent.ACTION_BATTERY_LOW
電源斷開/接入ACTION_POWER_DISCONNECTED / ACTION_POWER_CONNECTED
桌布變更Intent.ACTION_WALLPAPER_CHANGED
手機重啟Intent.ACTION_REBOOT
APK 安裝/卸載ACTION_PACKAGE_ADDED / ACTION_PACKAGE_REMOVED
SD 卡掛載/卸出ACTION_MEDIA_MOUNTED / ACTION_MEDIA_EJECT
系統設定/區域設定變更ACTION_CONFIGURATION_CHANGED / ACTION_LOCALE_CHANGED
儲存空間不足Intent.ACTION_DEVICE_STORAGE_LOW
鎖屏/解鎖ACTION_SCREEN_OFF / ACTION_SCREEN_ON
開機完成Intent.ACTION_BOOT_COMPLETED(需權限)

以上多數寫法完全同構:繼承 BroadcastReceiver、在 onReceive 中比對 Action、動態註冊與解除註冊即可,因此不再逐一貼上重複的程式碼。

6. 特例:飛行模式切換

飛行模式的處理方式略有不同,需要透過 ContentResolver 修改系統設定並手動發送廣播。佈局上放兩個按鈕:

<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/btn_startflying"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="開啟飛行模式" />

    <Button
        android:id="@+id/btn_stopflying"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="關閉飛行模式" />
</LinearLayout>
case R.id.btn_startflying:
    // 0 代表關閉,1 代表開啟
    if ("0".equals(Settings.System.getString(cr, Settings.System.AIRPLANE_MODE_ON))) {
        Settings.System.putString(cr, Settings.System.AIRPLANE_MODE_ON, "1");
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED)
                .putExtra("state", true);
        sendBroadcast(intent);
        Toast.makeText(this, "已開啟飛行模式", Toast.LENGTH_SHORT).show();
    }
    break;

case R.id.btn_stopflying:
    if ("1".equals(Settings.System.getString(cr, Settings.System.AIRPLANE_MODE_ON))) {
        Settings.System.putString(cr, Settings.System.AIRPLANE_MODE_ON, "0");
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED)
                .putExtra("state", false);
        sendBroadcast(intent);
        Toast.makeText(this, "已關閉飛行模式", Toast.LENGTH_SHORT).show();
    }
    break;

別忘了加上寫入設定的權限:

<uses-permission android:name="android.permission.WRITE_SETTINGS" />

Two:服務 Service

1. 基本認知

Service 類似於 Activity,同樣有自己的生命週期,但沒有使用者介面,主要在後台執行較長時間的工作。使用上分兩步:建立子類,然後在 AndroidManifest 中宣告(可透過 <intent-filter> 指定哪些 Intent 能啟動它)。

2. 兩組生命週期回呼

以 startService() 啟動:

  • onCreate():第一次建立服務時呼叫
  • onStartCommand():每次呼叫 startService() 都會觸發
  • onDestroy():服務關閉前呼叫

以 bindService() 綁定:

  • onCreate():第一次建立服務時呼叫
  • onBind():子類必須實作,回傳一個 IBinder 物件
  • onUnbind():所有客戶端都解除綁定時呼叫

3. 範例一:定時任務

這個範例示範如何用 AlarmManager 搭配 PendingIntent,週期性地啟動廣播或服務。佈局上放四顆按鈕:定時發送廣播、定時啟動服務、停止定時廣播、停止定時服務。

// 取得系統服務
am = (AlarmManager) getSystemService(ALARM_SERVICE);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

// 啟動:定時廣播
pi1 = PendingIntent.getBroadcast(SecondActivity.this, 0,
        new Intent(SecondActivity.this, ActionBroadCast.class),
        Intent.FILL_IN_ACTION);
long now = System.currentTimeMillis();
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, now, 3000, pi1);

// 啟動:定時服務
pi2 = PendingIntent.getService(SecondActivity.this, 0,
        new Intent(SecondActivity.this, ActionService.class),
        Intent.FILL_IN_ACTION);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, now, 3000, pi2);

// 停止
am.cancel(pi1);
am.cancel(pi2);

服務端只需要覆寫 onCreate 印出計數,就能觀察到週期性觸發的效果:

public class ActionService extends Service {
    private static int num = 0;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("ActionService", "New Message ! " + num++);
    }
}

廣播接收器同理,在 onReceive 中印出計數即可。這裡刻意使用 setInexactRepeating 而非 setRepeating,因為精確重複鬧鐘會顯著增加電量消耗,Android 也建議開發者優先採用不精確版本,讓系統自行合併調度。

4. 範例二:行車模式與夜間模式

駕車時開啟行車模式(來電自動接聽),夜間則切換到夜間模式。兩者都由系統服務 UiModeManager 負責:

uiModeManager = (UiModeManager) getSystemService(Context.UI_MODE_SERVICE);

// 行車模式
uiModeManager.enableCarMode(UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME);
uiModeManager.disableCarMode(UiModeManager.DISABLE_CAR_MODE_GO_HOME);

// 夜間模式
uiModeManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
uiModeManager.setNightMode(UiModeManager.MODE_NIGHT_NO);

佈局上同樣是四顆按鈕,分別對應開啟/關閉行車模式與夜間模式,點擊時呼叫上述方法並用 Toast 提示結果即可。

5. 範例三:音量控制

音量相關操作由 AudioManager 負責。它最有價值的部分是把音量細分為多個 stream:

audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

// 讀取各類音量
int currentCall   = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
int currentSystem = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
int currentMusic  = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int currentTip    = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);

// 調整音量
audioManager.adjustStreamVolume(AudioManager.STREAM_SYSTEM,
        AudioManager.ADJUST_RAISE, AudioManager.FX_FOCUS_NAVIGATION_UP);
audioManager.adjustStreamVolume(AudioManager.STREAM_SYSTEM,
        AudioManager.ADJUST_LOWER, AudioManager.FX_FOCUS_NAVIGATION_UP);

也就是說,「調音量」這件事在 Android 裡並不是單一概念:通話音量、系統提示音、音樂、鬧鐘各自獨立,實作前一定要先想清楚要操作的是哪一條 stream。

小結

廣播與服務的 API 都不算複雜,真正的難點在於「何時該用哪一種」。幾點實務經驗值得記住:

  • 動態註冊的接收器一定要記得解除註冊,否則會造成記憶體洩漏;把註冊與解除寫在同一組生命週期裡是最保險的做法。
  • 不要在 onReceive 裡做耗時工作。它的執行時間有限,超過會被系統判定 ANR;真正耗時的任務應該轉交給 Service 或 WorkManager。
  • Android 8.0 之後對背景服務與隱式廣播有諸多限制,上述部分 Action(如 ACTION_NEW_PICTURE 這類隱式廣播)已無法用 Manifest 靜態註冊,實作時請以目前版本的官方文件為準。

以上都只是基礎入門示範,後續還有更多細節可以深入。待續。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved