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

Android 後台 Service 入門:IntentService、廣播通信與通知欄進度

編輯:關於 Android 程式設計

本文整理 Android Service 的相關知識,會穿插一些延伸要點,適合初學者閱讀。老鳥可以直接跳過。

涵蓋內容:

  • 為什麼需要 Service
  • Service 與它的子類 IntentService
  • 用一個後台計數器把 Service 走一遍
  • Service 如何與 UI 組件通信

一、為什麼要用 Service

剛接觸 Android 時,我們大部分時間都在跟 Activity 打交道。但有些操作——網路下載、大檔案讀寫、資料解析——特點是耗時但不需要界面。如果把這些工作綁在 Activity 上,一旦頁面退出,情況就變得不可控:進度回調時 View 已被銷毀而報錯,或者下載直接中斷。即使你把各種異常都考慮得滴水不漏,也擋不住系統在記憶體緊張時把後台 Activity 回收掉,依附其上的執行緒跟著一起結束。

這正是 Service 的用武之地:不依賴界面、資源消耗少、優先級高於後台 Activity,不容易被系統回收(即便被回收,也能透過 START_STICKY 之類的標誌讓它自動重啟)。

二、Service 與 IntentService

Service 的生命週期

Service 的生命週期比 Activity 簡單不少:

它有兩條獨立的生命線:一條始於 startService(),另一條始於 bindService()。本文只討論 startService()。

先來一道選擇題:

透過 startService() 啟動服務,關於 onCreate() 和 onStartCommand() 的說法,正確的是哪兩項?

A. 第一次啟動時,先後呼叫 onCreate() 和 onStartCommand()
B. 第一次啟動時只呼叫 onCreate()
C. 若 service 已啟動,將先後呼叫 onCreate() 和 onStartCommand()
D. 若 service 已啟動,只執行 onStartCommand(),不再執行 onCreate()

答案先留著,文末公布。

IntentService

有一個容易被忽略的關鍵事實:Service 的程式碼跑在主執行緒上。也就是說,直接在上面寫耗時邏輯一樣會卡住 UI。為了解決這個問題,Android 提供了 IntentService。Android Studio 的新建模板裡直接就有 IntentService,可見其使用頻率。

兩者的差別可以這樣概括:

  • IntentService 內部有一個工作執行緒(Worker Thread),會把 startService() 傳入的 Intent 透過 Handler-Message 機制派送過去,開發者只需重載 onHandleIntent() 實作具體邏輯。
  • onHandleIntent() 跑完後,若佇列中已無其他訊息,服務會自動停止——有點像 Thread 的 run() 方法,跑完就結束。而原生 Service 需要自己呼叫 stopSelf() 或 stopService()。

三、實作一個後台計數器

接下來用一個計數器來模擬「下載檔案」這種耗時操作。

Activity 側的啟動程式碼:

public void startService(View view) {
    BackgroundService.startCounterService(this, 1, 10);
}

Service 內部對外暴露一個靜態方法,只把參數收進來,其餘細節全部封裝在內部:

public static void startCounterService(@NonNull Context context,
                                       int interval, int duration) {
    Intent intent = new Intent(context, BackgroundService.class);
    intent.setAction(ACTION_COUNTER);
    intent.putExtra(EXTRA_DURATION, duration);
    intent.putExtra(EXTRA_INTERVAL, interval);
    context.startService(intent);
}

在這裡,action 用來標識「要做什麼操作」(一個 Service 處理多種請求時特別有用),extra 則是參數。duration 代表總時長 10 秒,interval 代表每隔幾秒走一次。

private static final String ACTION_COUNTER =
        "com.example.administrator.servicestudy.action.counter";

@Override
protected void onHandleIntent(Intent intent) {
    if (intent != null) {
        final String action = intent.getAction();
        if (ACTION_COUNTER.equals(action)) {
            final int duration = intent.getIntExtra(EXTRA_DURATION, 0);
            final float interval = intent.getFloatExtra(EXTRA_INTERVAL, 0);
            handleActionCounter(duration, interval);
        }
    }
}

private void handleActionCounter(int duration, float interval) {
    for (int i = 0; i < duration; i++) {
        try {
            Thread.sleep((long) (interval * 1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        updateUI(i, duration);
    }
}

最後別忘了在 AndroidManifest 中聲明:

<service
    android:name=".BackgroundService"
    android:exported="false" />

把啟動邏輯寫成 Service 的靜態方法,雖然程式碼位置換了地方,但運行位置沒變(靜態方法仍在 Activity 側執行)。這樣做的好處是 EXTRA_DURATION、EXTRA_INTERVAL 這類參數不必外洩,封裝性和模組化都更好,值得推薦。

四、Service 如何與 UI 通信

Service 不依賴任何界面,因此自己沒辦法更新畫面(頂多用 Toast)。要讓用戶看到後台進度,就得靠組件間通信——最常見的搭檔是 Activity 和通知欄。

用廣播接收器(Broadcast)通信

Broadcast 的生命週期非常短:onReceive() 一旦執行完就被銷毀,沒有 onCreate,也沒有 onDestroy。

最重要的一條限制:不要在 onReceive() 裡做耗時操作,超過約 5 秒系統就會拋出 ANR。

Service 側發送廣播很簡單:

private void updateUI(int current, int total) {
    Intent intent = new Intent(BROADCAST_UPDATE_UI);
    intent.putExtra(EXTRA_CURRENT, current);
    intent.putExtra(EXTRA_TOTAL, total);
    sendBroadcast(intent);
}

Activity 側則在 onResume() 註冊、onPause() 反註冊:

@Override
protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter();
    filter.addAction(BackgroundService.BROADCAST_UPDATE_UI);
    registerReceiver(mBackgroundServiceReceiver, filter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mBackgroundServiceReceiver);
}

private BroadcastReceiver mBackgroundServiceReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (BackgroundService.BROADCAST_UPDATE_UI.equals(intent.getAction())) {
            int current = intent.getIntExtra(BackgroundService.EXTRA_CURRENT, 0);
            int total = intent.getIntExtra(BackgroundService.EXTRA_TOTAL, 0);
            mHint.setText(current + "/" + total);
        }
    }
};

進一步封裝:把 Receiver 收進 Service

如果希望 Activity 更乾淨,可以把廣播接收器寫成 Service 的靜態內部類,並在 Manifest 中靜態註冊:

<receiver android:name=".BackgroundService$BackgroundServiceReceiver">
    <intent-filter>
        <action android:name="com.example.administrator.servicestudy.UPDATE_UI" />
        <action android:name="com.example.administrator.servicestudy.FINISH" />
    </intent-filter>
</receiver>

注意類名中間那個美元符號,它是靜態內部類的標記。靜態註冊的接收器一直存在,不需要手動 register/unregister。

public static class BackgroundServiceReceiver extends BroadcastReceiver {
    private static List<UIHandler> mHandlers = new ArrayList<>();

    @Override
    public void onReceive(Context context, Intent intent) {
        if (BROADCAST_UPDATE_UI.equals(intent.getAction())) {
            int current = intent.getIntExtra(EXTRA_CURRENT, 0);
            int total = intent.getIntExtra(EXTRA_TOTAL, 0);
            for (UIHandler handler : mHandlers) {
                handler.onUpdateUI(current, total);
            }
        } else if (BROADCAST_FINISH.equals(intent.getAction())) {
            for (UIHandler handler : mHandlers) {
                handler.onFinish();
            }
        }
    }
}

public interface UIHandler {
    void onUpdateUI(int current, int total);
    void onFinish();
}

public static void registerUIHandler(UIHandler handler) {
    if (handler != null) {
        BackgroundServiceReceiver.mHandlers.add(handler);
    }
}

public static void unregisterUIHandler(UIHandler handler) {
    BackgroundServiceReceiver.mHandlers.remove(handler);
}

逐點說明:Manifest 中靜態註冊接收器;在 Service 內部實作 Receiver;定義一個 UIHandler 接口代表具體的界面更新行為;提供註冊與反註冊方法。由於一個 Service 可能同時更新多個界面組件,所以 mHandlers 是一個列表,收到廣播後逐一通知。

Activity 側就只剩註冊與反註冊:

@Override
protected void onResume() {
    super.onResume();
    BackgroundService.registerUIHandler(mServiceUIHandler);
}

@Override
protected void onPause() {
    super.onPause();
    BackgroundService.unregisterUIHandler(mServiceUIHandler);
}

private BackgroundService.UIHandler mServiceUIHandler = new BackgroundService.UIHandler() {
    @Override
    public void onUpdateUI(int current, int total) {
        mHint.setText(current + "/" + total);
    }

    @Override
    public void onFinish() {
        mHint.setText("Finished");
    }
};

這樣就完成了一次 Service 的封裝。我一直的習慣是:Activity 裡只放和界面相關的程式碼。就像 C 語言的 main 函式,你不会把全部邏輯都塞進去,也不會把所有函式寫在同一個檔案裡。

這裡有個行為需要留意:IntentService 內部其實是一個 Worker Thread,多次點擊 start 相當於往佇列裡多丟了幾條訊息,所以計數會在跑完之後重新開始。實際操作一下就能感受到。

停止服務

// Service
public static void stopCounterService(@NonNull Context context) {
    Intent intent = new Intent(context, BackgroundService.class);
    intent.setAction(ACTION_COUNTER);
    context.stopService(intent);
}

// Activity
public void stopService(View view) {
    BackgroundService.stopCounterService(this);
}

IntentService 是以 Message 為單位停止的,也就是說必須等當前訊息處理完才會真正結束。為此可以加一個標誌位,讓迴圈提前退出:

@Override
public void onCreate() {
    super.onCreate();
    mServiceFinished = false;
}

@Override
public void onDestroy() {
    super.onDestroy();
    mServiceFinished = true;
    Intent intent = new Intent(BROADCAST_FINISH);
    sendBroadcast(intent);
}

private void handleActionCounter(int duration, float interval) {
    for (int i = 0; i < duration; i++) {
        if (mServiceFinished) {
            break;
        }
        try {
            Thread.sleep((long) (interval * 1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        updateUI(i, duration);
    }
}

五、Service 與通知欄通信

到目前為止,Service 與 Activity 之間已經透過廣播打通:Service 負責邏輯,Activity 負責顯示。但你可能會想,這些程式碼寫在 Activity 裡似乎也行?確實,寫在 Service 裡主要是結構更清楚。可實際退出頁面再回來你會發現,計數並沒有因為 Activity 銷毀而中斷或暫停——這才是 Service 的價值所在。

接下來進入真正的「後台」場景:Activity 退出後,通知欄繼續顯示進度;點擊通知或重新進入 Activity 時,通知欄停止顯示(既避免重複,也順便演示程式碼)。

新建一個普通的 Service(這裡不需要耗時操作,連 onStartCommand() 都不用重載):

public class NotificationService extends Service {

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

    @Override
    public void onCreate() {
        super.onCreate();
        BackgroundService.registerUIHandler(mUIHandler);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BackgroundService.unregisterUIHandler(mUIHandler);
    }

    private BackgroundService.UIHandler mUIHandler = new BackgroundService.UIHandler() {
        @Override
        public void onUpdateUI(int current, int total) {
            // 點擊通知後啟動 Activity;FLAG_ONE_SHOT 表示只執行一次
            PendingIntent pendingIntent = PendingIntent.getActivity(
                    NotificationService.this, 0,
                    new Intent(NotificationService.this, MainActivity.class),
                    PendingIntent.FLAG_ONE_SHOT);

            NotificationManager nm =
                    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            Notification notification = new Notification.Builder(getApplicationContext())
                    .setContentTitle("Background Service")
                    .setTicker("Counting...")        // 狀態欄滾動文字
                    .setContentText("Ongoing")
                    .setProgress(total, current, false) // 內建進度條
                    .setOngoing(true)                // 是否可取消
                    .setContentIntent(pendingIntent)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setOnlyAlertOnce(true)          //  frequent 更新時避免音效鬼畜
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();

            // 第一個參數為通知 ID,App 內唯一;相同 ID 會更新原通知而非新增一條
            nm.notify(1234, notification);
        }

        @Override
        public void onFinish() {
            NotificationManager nm =
                    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            Notification notification = new Notification.Builder(getApplicationContext())
                    .setContentTitle("Background Service")
                    .setContentText("Finished")
                    .setOngoing(false)
                    .setContentIntent(null)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setOnlyAlertOnce(true)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();

            nm.notify(1232, notification);
            nm.cancel(1234);
        }
    };
}

Activity 側只要在 Resume 時關掉通知服務、Pause 時開啟即可:

@Override
protected void onResume() {
    super.onResume();
    stopService(new Intent(this, NotificationService.class));
}

@Override
protected void onPause() {
    super.onPause();
    startService(new Intent(this, NotificationService.class));
}

幾個通知 API 的實務提醒:

  • 不設定 PendingIntent 的通知不會顯示。
  • setOnlyAlertOnce(true) 幾乎是頻繁更新類通知的必備項,否則音效、震動、呼吸燈會瘋狂作響。
  • setProgress() 是系統內建的進度條,不必再自定義。
  • notify() 的 ID 在 App 內全域唯一,相同 ID 表示更新同一條通知。

最後補上收尾:服務銷毀時發送一個結束廣播,UI 層收到後把界面與通知都更新為「已完成」。這部分程式碼已包含在上面的 UIHandler.onFinish() 與 onDestroy() 中。

教學到此結束。文末公布前面那道選擇題的答案:A 和 D。

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