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

如何判斷 Android 應用是否已退到後台執行

編輯:關於 Android 程式設計

在 Android 開發過程中,我們時常需要確認自己的服務是否仍在後台運行。原因很單純:後台服務的優先級會被系統調降,也就更容易遭到回收。那麼該如何得知服務是否已退居後台呢?Google 的建議是將服務拉到前台執行,而判斷依據,則可以藉由取得任務堆疊、檢查棧頂的 Activity 是否屬於本應用來達成。

一、關鍵判斷程式碼

使用前別忘了先在清單中加上權限:

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

其中 mPackageName 代表本應用的套件名稱,mActivityManager 則是 Activity 管理物件:

mActivityManager = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
mPackageName = getPackageName();
public boolean isAppOnForeground() {
    List<RunningTaskInfo> tasksInfo = mActivityManager.getRunningTasks(1);
    if (tasksInfo.size() > 0) {
        L.i("top Activity = " + tasksInfo.get(0).topActivity.getPackageName());
        // 應用程式位於堆疊的頂層
        if (mPackageName.equals(tasksInfo.get(0).topActivity.getPackageName())) {
            return true;
        }
    }
    return false;
}

二、什麼時候呼叫這個方法?

接著會面臨一個新問題:究竟該在何時呼叫它?實務上有兩種思路——主動與被動。

① 主動方式:在服務中開啟一條執行緒,每隔一段時間就呼叫一次這個方法。

② 被動方式:自訂一個繼承自 Activity 的 BaseActivity,並在它的 onPause 中回呼通知服務,再讓應用內的所有 Activity 都繼承這個 BaseActivity,如此一來便能掌握棧頂是否還有本應用的 Activity。

三、將服務切換為前台執行

當我們確認棧頂已不是本應用的 Activity,服務的優先級也會隨之降低,一旦系統需要記憶體,這個服務就會優先被回收。此時只需把它設為前台執行即可:

① 設為前台:第一個參數是通知 ID,第二個參數是 Notification 物件。

startForeground(SERVICE_NOTIFICATION, n);

② 停止前台服務可呼叫(true 代表同時清除通知欄):

stopForeground(true);
public void updateServiceNotification(String message) {
    if (!PreferenceUtils.getPrefBoolean(this, PreferenceConstants.FOREGROUND, true)) return;
    String title = PreferenceUtils.getPrefString(this, PreferenceConstants.ACCOUNT, "");
    Notification n = new Notification(R.drawable.login_default_avatar, title, System.currentTimeMillis());
    n.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    n.contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    n.setLatestEventInfo(this, title, message, n.contentIntent);
    startForeground(SERVICE_NOTIFICATION, n);
}

// 判斷程式是否退到後台的週期性任務
Runnable monitorStatus = new Runnable() {
    public void run() {
        try {
            L.i("monitorStatus is running... " + mPackageName);
            mMainHandler.removeCallbacks(monitorStatus);
            // 如果在後台運行
            if (!isAppOnForeground()) {
                L.i("app run in background...");
                updateServiceNotification(getString(R.string.run_bg_ticker));
                return; // 服務已在前台運行,可停止重複執行
            } else {
                stopForeground(true);
            }
            mMainHandler.postDelayed(monitorStatus, 1000L);
        } catch (Exception e) {
            e.printStackTrace();
            L.i("monitorStatus:" + e.getMessage());
        }
    }
};

以上僅是筆者的一點實作心得,若有思考不周之處,还请各位讀者明辨採用。

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