編輯:關於 Android 程式設計
1)Service 重啟
2)進程守護
3)Receiver 觸發
4)AlarmManager 或 JobScheduler 循環觸發
5)與系統 Service 綁定(瞭解即可)
下面圍繞這幾點逐一展開討論。
1. 什麼才算應用進程保活
應用進程保活,可以理解為讓應用位於後台時永不被殺死。這裡可粗略分為兩種情況:第一種是系統資源緊張時,或基於某種系統自身的後台運行規則,選擇殺掉你的後台應用來釋放資源;第二種是用戶手動調用某些安全軟件的清理功能,把後台應用清掉。對於 Android 5.0 以前的系統,我們可以同時考慮這兩種情況下的後台常駐;而對於 Android 5.0 及以後的版本,則只能著眼於第一種情況,因為從 5.0 開始,系統對進程的管理更為嚴格,殺得也更為徹底。
2. Android 進程的生命週期
Android 系統會盡力保持應用的進程,但有時為了給新進程和更重要的進程騰出記憶體,它會移除一些舊進程。為了決定誰去誰留,系統會依據進程中運行的元件及其狀態,為每個進程分配一個優先級等級,優先級最低者最先被殺。這個重要性層級共有五等,以下按重要性由高到低排列:
1)前台進程 Foreground process
處於此狀態的進程代表它當前正與用戶互動,是必須存在的,除非系統出錯或用戶手動殺掉,否則系統不會去動它。系統透過哪些規則判斷一個進程是否為前台進程呢?以下是一些具體情境:
某進程持有一個正與用戶互動、且處於 resume 狀態的 Activity;
某進程持有一個 Service,且該 Service 與用戶正在互動的 Activity 綁定;
某進程持有一個 Service,且該 Service 呼叫了 startForeground() 使其位於前台運行;
某進程持有一個 Service,且該 Service 正在執行它的某個生命週期回調,如 onCreate()、onStart() 或 onDestroy();
某進程持有一個 BroadcastReceiver,且該 BroadcastReceiver 正在執行其 onReceive() 方法。
可見讓進程位於前台的方式還不少。但要提醒的是,Android 是一個碎片化極其嚴重的系統,很多定制 ROM 都會修改部分系統邏輯來做所謂的「優化」,所以上述情境以及後文提到的其他進程狀態,實際上都只能保證在原生系統上完美生效;到了某些定制 ROM 上,則可能失效甚至出現詭異的現象。
2)可見進程 Visible process
可見進程比前台進程簡單得多。它不包含任何前台元件,也就是說不會出現上述前台進程的任何情境;但它依然會影響用戶在螢幕上看到的內容。常見的可見進程情境可分為兩種:
某進程持有一個 Activity,該 Activity 並非位於前台但仍能被用戶看到——從程式碼邏輯上講,就是呼叫了 onPause() 卻還沒呼叫 onStop() 的狀態;視覺上常見的情形,是當一個 Activity 彈出一個非全螢幕的 Dialog 時;
某進程持有一個 Service,且該 Service 和一個可見(或前台)的 Activity 綁定。
3)服務進程 Service process
服務進程好理解很多:若某進程中運行著一個透過 startService() 啟動的 Service,也就是沒有與任何 Activity 綁定、也不屬於上述兩種狀態,那麼該進程就是一個服務進程。
4)後台進程 Background process
這裡要特別注意:此處所說的「後台進程」只是進程的一種狀態,與我們前後文中提到的「後台進程」是兩個概念,切莫混淆。當進程處於後台進程狀態時,它一般持有一個不可見的 Activity,也就是 Activity 隱藏到後台但尚未退出——從程式碼邏輯上講,就是該 Activity 的 onStop 已被呼叫、但 onDestroy 尚未執行的狀態。後台進程會被系統存進一個 LRU 表,以確保最近使用的進程最後才被銷毀。
5)空進程 Empty process
若一個進程不包含任何活躍的應用元件,則被視為空進程。保留這種進程的唯一理由,是為了快取需要——加快下次啟動該進程元件的速度。系統為了平衡進程快取與底層核心快取的資源,經常會殺死空進程。
這五種狀態對系統而言的重要性由上而下遞減:空進程最容易被殺,其次是後台進程,再來是服務進程乃至可見進程,而前台進程一般不會被輕易動。系統殺進程遵循一套規則,而這套規則建立在系統可用資源的基礎上。打個比方:若設備有高達 3GB 執行記憶體、可用還有 2GB,那麼即便是空進程系統也不會去動它;反之,若設備只有 256M 記憶體、可用不足 16M,這時即便是可見進程也會被系統列入考慮。這套依系統資源決定殺誰的規則,Android 稱之為 Low Memory Killer。此外,Android 在上述五種狀態之上還衍生出更多進程相關的定義,其中比較重要的兩個是進程的 Importance 等級與 adj 值。這兩個概念大家不必深究,但要有一定理解——它們具體決定了資源吃緊時系統該殺掉哪些進程。Importance 等級在 ActivityManager.RunningAppProcessInfo 中宣告:
public static class RunningAppProcessInfo implements Parcelable { /** * Constant for {@link #importance}: This process is running the * foreground UI; that is, it is the thing currently at the top of the screen * that the user is interacting with. */ public static final int IMPORTANCE_FOREGROUND = 100; /** * Constant for {@link #importance}: This process is running a foreground * service, for example to perform music playback even while the user is * not immediately in the app. This generally indicates that the process * is doing something the user actively cares about. */ public static final int IMPORTANCE_FOREGROUND_SERVICE = 125; /** * Constant for {@link #importance}: This process is running the foreground * UI, but the device is asleep so it is not visible to the user. This means * the user is not really aware of the process, because they can not see or * interact with it, but it is quite important because it what they expect to * return to once unlocking the device. */ public static final int IMPORTANCE_TOP_SLEEPING = 150; /** * Constant for {@link #importance}: This process is running something * that is actively visible to the user, though not in the immediate * foreground. This may be running a window that is behind the current * foreground (so paused and with its state saved, not interacting with * the user, but visible to them to some degree); it may also be running * other services under the system's control that it inconsiders important. */ public static final int IMPORTANCE_VISIBLE = 200; /** * Constant for {@link #importance}: This process is not something the user * is directly aware of, but is otherwise perceptable to them to some degree. */ public static final int IMPORTANCE_PERCEPTIBLE = 130; /** * Constant for {@link #importance}: This process is running an * application that can not save its state, and thus can't be killed * while in the background. * @hide */ public static final int IMPORTANCE_CANT_SAVE_STATE = 170; /** * Constant for {@link #importance}: This process is contains services * that should remain running. These are background services apps have * started, not something the user is aware of, so they may be killed by * the system relatively freely (though it is generally desired that they * stay running as long as they want to). */ public static final int IMPORTANCE_SERVICE = 300; /** * Constant for {@link #importance}: This process process contains * background code that is expendable. */ public static final int IMPORTANCE_BACKGROUND = 400; /** * Constant for {@link #importance}: This process is empty of any * actively running code. */ public static final int IMPORTANCE_EMPTY = 500; /** * Constant for {@link #importance}: This process does not exist. */ public static final int IMPORTANCE_GONE = 1000; }而 adj 值則在 ProcessList 中定義:
final class ProcessList { // OOM adjustments for processes in various states: // Adjustment used in certain places where we don't know it yet. // (Generally this is something that is going to be cached, but we // don't know the exact value in the cached range to assign yet.) static final int UNKNOWN_ADJ = 16; // This is a process only hosting activities that are not visible, // so it can be killed without any disruption. static final int CACHED_APP_MAX_ADJ = 15; static final int CACHED_APP_MIN_ADJ = 9; // The B list of SERVICE_ADJ -- these are the old and decrepit // services that aren't as shiny and interesting as the ones in the A list. static final int SERVICE_B_ADJ = 8; // This is the process of the previous application that the user was in. // This process is kept above other things, because it is very common to // switch back to the previous app. This is important both for recent // task switch (toggling between the two top recent apps) as well as normal // UI flow such as clicking on a URI in the e-mail app to view in the browser, // and then pressing back to return to e-mail. static final int PREVIOUS_APP_ADJ = 7; // This is a process holding the home application -- we want to try // avoiding killing it, even if it would normally be in the background, // because the user interacts with it so much. static final int HOME_APP_ADJ = 6; // This is a process holding an application service -- killing it will not // have much of an impact as far as the user is concerned. static final int SERVICE_ADJ = 5; // This is a process with a heavy-weight application. It is in the // background, but we want to try to avoid killing it. Value set in // system/rootdir/init.rc on startup. static final int HEAVY_WEIGHT_APP_ADJ = 4; // This is a process currently hosting a backup operation. Killing it // is not entirely fatal but is generally a bad idea. static final int BACKUP_APP_ADJ = 3; // This is a process only hosting components that are perceptible to the // user, and we really want to avoid killing them, but they are not // immediately visible. An example is background music playback. static final int PERCEPTIBLE_APP_ADJ = 2; // This is a process only hosting activities that are visible to the // user, so we'd prefer they don't disappear. static final int VISIBLE_APP_ADJ = 1; // This is the process running the current foreground app. We'd really // rather not kill it! static final int FOREGROUND_APP_ADJ = 0; // This is a process that the system or a persistent process has bound to, // and indicated it is important. static final int PERSISTENT_SERVICE_ADJ = -11; // This is a system persistent process, such as telephony. Definitely // don't want to kill it, but doing so is not completely fatal. static final int PERSISTENT_PROC_ADJ = -12; // The system process runs at the default adjustment. static final int SYSTEM_ADJ = -16; // Special code for native processes that are not being managed by the system (so // don't have an oom adj assigned by the system). static final int NATIVE_ADJ = -17; }Importance 等級與 adj 值在 ActivityManagerService 中被關聯起來。相較於 Importance 等級,adj 值能給我們更多參考價值。從上述定義可以看到,值越小優先級越高:比如 native 進程的 adj 值為 -17,對於這種進程,系統根本不會動它分毫;實際上,當進程的 adj 值降到 2 時,系統就很少會因其他原因殺死它了。日常開發中,我們可以透過查看 proc 目錄下相關進程的節點來取得其 adj 值:
adb shell cat /proc/32366/oom_adj注意「32366」是進程 ID,你可以透過前面提到的 ps 命令取得相關進程的 ID。cat 查看後會得到返回結果「0」,說明當前進程正位於前台;此時我們按返回鍵退出應用後再次查看,會發現 adj 值變成了「8」,也就是說進程優先級變得很低了。這裡要留意,上述操作均在原生 Android 系統上執行,若是其他定制 ROM,輸出與結果可能有出入——adj 值僅能作為參考,而非絕對的常量。
說了這麼多,我們也差不多能歸納出一套規律。要讓後台進程長存,首先要應付的就是系統的「自殺」機制;而後台進程被殺的首要原因,就是進程優先級太低、同時系統可用資源太少。其次,如果真的被系統干掉,那我們得設法重新把它拉起。因此,進程後台常駐策略最終可歸結為兩點:
1. 輕量化進程
所謂輕量化進程,就是迫使我們的進程盡可能少佔資源。但我們知道,一個運行中的 App 就算功能再少,也會佔去不少資源。因此,我們不該指望應用的主進程在後台常駐——讓一個沒有可見介面的進程在後台跑,既沒意義也沒必要。大多數情況下,我們會另開一個新進程來常駐後台,而這個進程通常會持有一個 Service,後台所有「見不得光」的活儿都交給它處理,畢竟在 Android 裡能干這種事的也只有 Service 了:
如上所示,我們宣告一個 service,並透過 startService 啟動它。在這個 Service 裡,我們用一個迴圈不斷 Toast 一段訊息:
package com.test.daemon.services; import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.SystemClock; import android.widget.Toast; /** * * @author caoyinfei * @version [版本號, 2016/5/11] * @see [相關類/方法] * @since [產品/模塊版本] */ public class DaemonService extends Service { private static boolean sPower = true; private Handler handler = new Handler(); @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { new Thread(new Runnable() { @Override public void run() { while (sPower) { if (System.currentTimeMillis() >= 123456789000000L) { sPower = false; } handler.post(new Runnable() { @Override public void run() { Toast.makeText(DaemonService.this, "====" + System.currentTimeMillis(), Toast.LENGTH_SHORT).show(); } }); SystemClock.sleep(3000); } } }).start(); return super.onStartCommand(intent, flags, startId); } }如果你想在 Service 裡處理更複雜的邏輯,務必盡量多用弱參照或軟參照,或盡量把不必要的參照置空、需要時再賦值;此外,Service 本身提供了 onTrimMemory 方法,用來告訴我們系統何時需要釋放不必要的資源,靈活使用這類方法,能最大程度讓後台 Service 長盛不衰。還是那句話:盡量讓後台進程做更少的事、及時釋放資源,才是硬道理。
2. 被殺後重啟
可以這麼說,沒有任何一個應用進程能做到永不被殺死,除非系統給你開了後門。進程被殺並不可怕,可怕的是殺掉後就永遠起不來了。那要如何讓進程在被殺後重啟呢?這就要用到所謂的守護進程。原理很簡單:多開一個進程,讓它輪詢檢查目標進程是否存活,死了就拉起;同時目標進程也做一個輪詢,檢查守護進程是否存活,死了也把它拉起,兩者相互喚醒、一起「苟活」。即便如此,意外有時仍難免,而在 Android 中,我們還能透過 AlarmManager 與系統廣播,在特定條件下喚醒逝去的進程。後文會詳細說明。
1. 盡量保證進程不被殺死
前面說到,adj 值越小的進程越不容易被殺死。對普通進程而言,能讓 adj 降到 0 顯然是最理想的。可是,一個完全沒有可見元素的後台進程,要如何才能擁有前台進程的狀態呢?Android 給了 Service 這樣一個能力:startForeground。顧名思義,它把 Service 置於前台,代價是你得發送一個 Notification:
public class DaemonService extends Service { @Override public void onCreate() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { Notification.Builder builder = new Notification.Builder(this); builder.setSmallIcon(R.mipmap.ic_launcher); startForeground(250, builder.build()); } else { startForeground(250, new Notification()); } } }值得留意的是,在 Android 4.3 以前,我們可以構造一個空的 Notification,此時通知欄並不會顯示我們發送的通知;但自 4.3 起,Google 似乎意識到了這個問題——太多流氓應用透過此法悄悄把自己置於前台,於是從 4.3 開始不再允許構造空 Notification。你若想把應用置於前台,就必須發送一個可見的通知,告知用戶你的進程仍在後台運行。這就比較棘手了:本想在後台悄悄運行,如今卻非得露出來。因此我們得想辦法把這個通知「做掉」。上面的程式碼裡,我們發送 Notification 時給了它一個唯一 ID。那麼問題來了:假如我啟動另一個 Service,同時也讓它發送一個 ID 相同的 Notification 把自己置於前台,然後再把它取消、並停止這個 Service 的前台顯示,會怎樣呢?
public class DaemonService extends Service { @Override public void onCreate() { super.onCreate(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { Notification.Builder builder = new Notification.Builder(this); builder.setSmallIcon(R.mipmap.ic_launcher); startForeground(250, builder.build()); startService(new Intent(this, CancelService.class)); } else { startForeground(250, new Notification()); } } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } } public class CancelService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { Notification.Builder builder = new Notification.Builder(this); builder.setSmallIcon(R.mipmap.ic_launcher); startForeground(250, builder.build()); new Thread(new Runnable() { @Override public void run() { SystemClock.sleep(1000); stopForeground(true); NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); manager.cancel(250); stopSelf(); } }).start(); } return super.onStartCommand(intent, flags, startId); } } tips:
android:enabled="true" 這個屬性值得留意。它用來標示其他應用的元件是否可以喚醒這個 service 或與之互動:true 表示可以,false 表示不可以。若為 false,只有同一應用的元件、或有相同 user ID 的應用才能啟動或綁定這個 service。
其預設值取決於當前 service 是否有 intent filter。若完全沒有 filter,意味著該 service 只有在被明確描述 class name 後才會被喚醒,也就只能在應用內部使用(因為外部應用不知道這個 class name),此時預設值為 false;反之,若至少有一個 filter,就意味著該 service 可被外部應用使用,此時預設值為 true。
其實,不只有這個屬性能指定 service 是否對外暴露,你也可以用 permission 來限制外部實體喚醒當前 service。
如程式碼所示,我們先在 DaemonService 中發送一個 Notification 並將其置於前台,接著若是 4.3 及以上版本,就啟動另一個 CancelService。CancelService 的邏輯很簡單:發送一個與 DaemonService 中 ID 相同的 Notification,然後把它取消並取消自己的前台顯示,再停止自己。看到這裡你或許覺得很奇葩——其實我們就是自導自演演了出戲,只是個小技巧而已。雖然透過 CancelService 干掉了前台顯示所需的通知,但請你查一下當前進程的 adj 值,就會發現 DaemonService 所在的進程竟然還是可見進程!

不過這些方法意義都不會很大。
2. 進程被殺死後復活
任何一個普通的應用進程,都會有被干掉的那一天,除非你跟系統「有關係、有契約」——說白了就是 ROM 是定制的、能給你開特殊權限。否則,系統總會在某個時刻因某些原因把你殺掉。被殺掉不可怕,可怕的是殺掉後再也活不過來。因此,我們得制定各種策略,好讓進程在被殺後能自啟。
1)Service 重啟
Android 的 Service 是一個非常特殊的元件,官方說法是它用來處理應用的某些不可見後台操作。我們都知道,透過在 onStartCommand 方法中返回不同的值,可以告知系統:當 Service 因資源吃緊被干掉後,可在資源不緊張時重啟。
@Override public int onStartCommand(Intent intent, int flags, int startId) { return START_REDELIVER_INTENT; }關於 onStartCommand 的返回值,系統一共提供了四種:
START_STICKY
若 Service 進程因系統資源吃緊而被殺掉,則保留 Service 的狀態為起始狀態,但不保留傳入的 Intent 物件;隨後當系統資源不緊張時,會嘗試重新建立 Service。由於服務狀態為開始狀態,所以建立後一定會呼叫 onStartCommand 方法;若在此期間沒有任何啟動命令傳入,那麼參數 Intent 將為 null。
START_STICKY_COMPATIBILITY
START_STICKY 的相容版本,不同的是它不保證服務被殺後一定能重啟。
START_NOT_STICKY
與 START_STICKY 恰恰相反:若返回該值,執行完 onStartCommand 後如果 Service 被殺掉,系統將不會重啟該服務。
START_REDELIVER_INTENT
與 START_STICKY 不同的是,START_STICKY 重啟後不會再傳遞之前的 Intent;而若返回該值,系統會把上次的 Intent 重新傳入。
一般情況下,作為一個後台常駐的 Service,個人建議盡量不要傳遞 Intent 進來,以免邏輯不好處理。同時要留意,預設情況下 Service 的返回值就是 START_STICKY 或 START_STICKY_COMPATIBILITY。因此若沒有特殊原因,我們也沒必要更改。雖然 Service 預設可被系統重啟,但在某些情況或某些定制 ROM 上會因各種原因失效,所以我們不能單靠這個返回值來達到進程重啟的目的。
2)進程守護
進程守護其實並不高深,邏輯也很簡單:A、B 兩個進程,A 進程裡輪詢檢查 B 是否存活,沒存活就拉起;同樣 B 進程裡輪詢檢查 A 是否存活,沒存活也把它拉起。而後台邏輯則隨便放在某個進程裡執行即可。一個簡單的例子是使用兩個 Service:
用兩個進程分別裝載兩個 Service,在兩個 Service 中開輪詢、互相喚醒:
public class DaemonService extends Service { private static boolean isRunning; @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (!isRunning) { isRunning = true; new Thread(new Runnable() { @Override public void run() { startService(new Intent(DaemonService.this, ProtectService.class)); SystemClock.sleep(3000); } }).start(); } return super.onStartCommand(intent, flags, startId); } } public class ProtectService extends Service { private static boolean isRunning; @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (!isRunning) { isRunning = true; new Thread(new Runnable() { @Override public void run() { SystemClock.sleep(1500); startService(new Intent(ProtectService.this, DaemonService.class)); } }).start(); } return super.onStartCommand(intent, flags, startId); } }在原生系統及相当一部分 ROM 下,上述方法已經很有用——即便應用主進程被用戶在 Recent Task 中清理,也不影響上述進程運行。該方法直至 Android 6.0 也相當有效,但對於一些深度定制的 ROM 就顯得雞肋,比如魅族、小米。
有些時候,我們會用一個更「純淨」的進程來做守護進程,而非借助 Service。你可以用 C 層 fork,也可以直接用 Java 建立一個新進程。在 5.0 以前,這兩種方式建立的進程有一定區別,但 5.0 以後已不再那麼重要。不依賴 Android 環境的進程,唯一的好處是可以做得更輕量,除此之外別無他用。這裡以 Java 為例:用 Java 建立進程有兩種途徑,一是透過 Runtime,二是透過 ProcessBuilder,後者提供了更多選擇。用 ProcessBuilder 建立進程也很簡單,三步曲——建立環境變數、指定用戶目錄、執行命令(這裡不詳細介紹)。
3)Receiver 觸發
用 Receiver 來檢測目標進程是否存活,也不失為一個好方法:靜態註冊一系列廣播,比如開機啟動、網絡狀態變化、時區地區變化、充電狀態變化等等。聽起來很美好,而且在大部分手機上都可行;但對於深度定制的 ROM——是的,又是深度定制,你沒看錯,而且代表人物還是魅族、小米,這兩個業界出了名喜歡「深度定制」系統的廠商。
大部分手機可行的方案如下:
在眾多 Intent 的 action 動作中,Intent.ACTION_TIME_TICK 比較特殊。根據 SDK 描述:
Broadcast Action: The current time has changed. Sent every minute. You can not receive this through components declared in manifests, only by exlicitly registering for it with Context.registerReceiver()
意思是說,這個廣播動作以每分鐘一次的形式發送;但你不能透過在 manifest.xml 裡註冊的方式接收它,只能在程式碼裡透過 registerReceiver() 方法註冊。
1. 在 manifest 裡註冊 TIME_TICK 廣播
2. 服務裡面註冊廣播
/** * 調用startForeground,提高進程adj值 * 該進程為需要保護的進程 */ public class DaemonService extends Service { private static boolean isRunning; AlarmManager mAlarmManager = null; PendingIntent mPendingIntent = null; @Override public void onCreate() { super.onCreate(); //服務啟動廣播接收器,使得廣播接收器可以在程序退出後在後天繼續執行,接收系統時間變更廣播事件 TimeChangeReceiver receiver=new TimeChangeReceiver(); registerReceiver(receiver,new IntentFilter(Intent.ACTION_TIME_TICK)); } 3. 廣播裡面判斷服務是否存在,不存在則開啟服務。
public class TimeChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //啟動service boolean isServiceRunning = false; System.out.println("TimeChangeReceiver"); if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) { //檢查Service狀態 ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if ("so.xxxx.xxxxService".equals(service.service.getClassName())) { isServiceRunning = true; } } if (!isServiceRunning) { Intent i = new Intent(context, DaemonService.class); context.startService(i); } } } } 自從 Android 3.1 開始,系統為我們的應用增加了一種叫做 STOPPED 的狀態。什麼叫 STOPPED?就是安裝之後從未啟動過的狀態。大家可能常在网上看到對開機廣播的解釋,說要想應用正確接收到開機廣播,就得先啟動一下應用——這個說法的技術支持正來源於此。因為自 Android 3.1 後,所有系統廣播都會在 Intent 加上一個叫 FLAG_EXCLUDE_STOPPED_PACKAGES 的標識,說白了就是所有處於 STOPPED 狀態的應用都不能接收到系統廣播。是不是覺得很蛋疼?沒事,更蛋疼的還在後面。在原生系統中,應用初次啟動後就會被標識為非 STOPPED 狀態,而且再也沒有機會被打回原形,除非重新安裝。但是——一些深度定制的 ROM 按捺不住了:這樣搞下去,如果每個應用都這麼玩,後台豈不是一大堆進程在跑?所以這些深度定制 ROM 會在它們的清理邏輯中,比如小米的長按 Home、魅族的 Recent Task,加入將應用重置為 STOPPED 的邏輯,也就是直接或間接地呼叫 ActivityManagerService 中的 forceStopPackageLocked:
private void forceStopPackageLocked(final String packageName, int uid, String reason) { // 省略一行代碼…… Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED, Uri.fromParts("package", packageName, null)); // 省略多行代碼…… broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid)); }可以看到,上面的程式碼裡發送了一個 ACTION_PACKAGE_RESTARTED 廣播,這個廣播會呼叫 broadcastIntentLocked 等方法,把相應的應用重置為 STOPPED 狀態。因此一旦我們的應用被重置為 STOPPED,就再也無法接收到相應的系統廣播,除非再次啟動一下應用、清掉 STOPPED 標識。
4) AlarmManager 或 JobScheduler 循環觸發
用 AlarmManager 間隔一段時間來檢測並喚醒進程,也不失為一個好方法。雖然從 Android 4.4 和小米的某些版本開始,AlarmManager 已經變得不再準確,但對我們拉活進程來說,並不需要太精確的時間。對於 4.4 以前的版本,只需透過 AlarmManager 的 setRepeating 方法即可達到目的:
Intent sendIntent = new Intent(getApplicationContext(), DaemonService.class); mAlarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); mPendingIntent = PendingIntent.getService(this, 0, sendIntent, PendingIntent.FLAG_UPDATE_CURRENT); long now = System.currentTimeMillis(); mAlarmManager.setInexactRepeating(AlarmManager.RTC, now, 60000, mPendingIntent);而對於 4.4 及以後的版本,如果我們想精確地重複啟動,就得使點小手段。4.4 起,Android 提供了一個新 API:setExact,顧名思義就是精確啟動。但與之前版本不同的是,4.4 開始並不能精確地「重複」啟動,也就是不能像 setRepeating 那樣,setExact 只能被喚醒一次。那要如何做到重複精確呢?其實很簡單:每次透過 AlarmManager 喚醒時都發送一個廣播,在這個廣播裡處理一些必要邏輯,爾後又設定一次 AlarmManager,如此往復循環,實質就是對廣播做一個遞歸以達到目的:
public class DReceiver extends BroadcastReceiver { private PendingIntent mPendingIntent; private AlarmManager am; @Override public void onReceive(Context context, Intent intent) { if (null == intent) return; if (null == mPendingIntent) { Intent i = new Intent(context, DReceiver.class); i.putExtra("time", System.currentTimeMillis() + 3000); mPendingIntent = PendingIntent.getService(context, 0x123, i, PendingIntent.FLAG_UPDATE_CURRENT); } if (null == am) am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); long time = intent.getLongExtra("time", System.currentTimeMillis()); am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, time, mPendingIntent); } }上述程式碼中我們用 Intent 來傳遞資料,事實上我們應該用持久化的資料來存儲這個 time 值,盡量少用甚至不用 Intent。
看到這裡,很多朋友會問是不是 OK 了?很遺憾地告訴你:NO!為什麼呢?不知道大家是否在開發中遇到過這樣的問題:你設定的 Alarm 在應用退出後,過不了多久居然就失效了,尤其是在某些深度定制的系統上。前面我們提到,Receiver 一旦應用被置為 STOPPED 狀態就再無法接收到廣播,很不幸,AlarmManager 也一樣。在 AlarmManagerService 中有一個 BroadcastReceiver,它會接收前面說的 ACTION_PACKAGE_RESTARTED 廣播:
class UninstallReceiver extends BroadcastReceiver { public UninstallReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addAction(Intent.ACTION_PACKAGE_RESTARTED); filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART); filter.addDataScheme("package"); getContext().registerReceiver(this, filter); // 省去幾行代碼…… } @Override public void onReceive(Context context, Intent intent) { synchronized (mLock) { String action = intent.getAction(); String pkgList[] = null; if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) { // 省去幾行代碼…… } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); } else if (Intent.ACTION_USER_STOPPED.equals(action)) { // 省去幾行代碼…… } else if (Intent.ACTION_UID_REMOVED.equals(action)) { // 省去幾行代碼…… } else { // 省去幾行代碼…… Uri data = intent.getData(); if (data != null) { String pkg = data.getSchemeSpecificPart(); if (pkg != null) { pkgList = new String[]{pkg}; } } } if (pkgList != null && (pkgList.length > 0)) { for (String pkg : pkgList) { removeLocked(pkg); // 省去幾行代碼…… } } } } }從上述源碼來看,當該廣播接收者收到 ACTION_PACKAGE_RESTARTED 廣播時,會執行 removeLocked 這個方法。這個方法就像它的名字那樣,會移除掉與應用相關的 Alarm 並刷新 Alarm 的狀態:
void removeLocked(String packageName) { boolean didRemove = false; for (int i = mAlarmBatches.size() - 1; i >= 0; i--) { Batch b = mAlarmBatches.get(i); didRemove |= b.remove(packageName); if (b.size() == 0) { mAlarmBatches.remove(i); } } for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) { if (mPendingWhileIdleAlarms.get(i).operation.getTargetPackage().equals(packageName)) { mPendingWhileIdleAlarms.remove(i); } } if (didRemove) { rebatchAllAlarmsLocked(true); rescheduleKernelAlarmsLocked(); updateNextAlarmClockLocked(); } }因此,對於某些手機在清理應用時會將其置為 STOPPED 狀態而言,即便設定了 AlarmManager 也是白搭。
與 AlarmManager 類似的、在 5.0 新鮮出爐的 JobScheduler,相比之下要比 AlarmManager 好一些;鑒於兩者原理類似,這裡就不再贅述。
5)與系統 Service 綁定
Android 系統提供給我們一系列 Service(注意,這裡指的並非「SystemService」提供的那些東西,而是類似系統廣播那樣便於我們使用的 Service),最常見的就是 IntentService,當然還有更多不常用的系統 Service。那為什麼要在這裡提到它們呢?因為某些系統 Service 一旦綁定,就像開了掛一樣擁有極大權限,這在大部分機型(包括某些深度定制系統)上簡直如同 BUG 般存在。以最 BUG 的 NotificationListenerService 為例——大家可能很少用到它,它是用來讀取通知的,也就是說只要是通知,不管誰發的,它都能檢測到。使用它也很簡單,和 IntentService 一樣,定義一個類繼承一下即可:
package teach.focus.notificatio; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; public class DService extends NotificationListenerService { @Override public void onNotificationPosted(StatusBarNotification sbn) { } @Override public void onNotificationRemoved(StatusBarNotification sbn) { } }裡面什麼邏輯都不用實作——是的你沒聽錯,什麼邏輯都不需要。然後在 AndroidManifest 中宣告權限:
這裡為了區別主進程,我把該 Service 置於一個單獨的進程中,然後啟動應用。注意,這裡我們的應用什麼邏輯都沒有,剔除掉上面所有有關進程保護的邏輯,運行之後你會發現看不到 NotificationListenerService 所在的進程。
先別急,NotificationListenerService 是個特殊的系統 Service,需要非常特別的權限,需要你手動到「設定-提示音和通知-通知使用權限」中打開。注意這個「通知使用權限」選項:如果你的設備裡沒有需要使用通知使用權限(換句話說,沒有含 NotificationListenerService 的應用)的話,這個設定選項是不可見的。所以,你想好如何騙用戶勾選這個勾勾了嗎?一旦勾上,一發不可收拾,這時你就會看到我們的進程啟動起來了。
好了,見證奇蹟的時候到了。不管是某米、某族還是某某,請試試它們的一鍵清理,你會發現不管怎麼殺,我們的進程都還在——除了一小部分名不經傳的手機因為修改系統邏輯把它殺死外,絕大部分手機都不會殺掉該進程。為什麼呢?好事的朋友一定會去 check 該進程的 adj 值:
root@vbox86p:/ # ps|grep notification u0_a1701 10615 286 762696 27832 sys_epoll_ 00000000 S teach.focus.notification root@vbox86p:/ # cat /proc/10615/oom_adj 0你會發現我們的進程被置為前台進程了,而且不僅如此——即便你重啟設備開機,它也會首先被啟動,因為其內部邏輯會使其在系統啟動時綁定並開始監聽通知。當然我們這裡並沒有任何關於通知的邏輯,那你可能會問,這又有什麼用呢?我們又不能把與通知不相關的邏輯塞進 NotificationListenerService 裡。沒錯,是這樣,但我們也沒必要啊——我們只需新建一個 Service,並讓它與 NotificationListenerService 處在同一進程下,那麼我們的這個 Service 不就一樣不死了嗎:
這種方式唯一的缺點,是你需要騙用戶手動去開啟通知權限,得給用戶一個合理的理由。所以對於跟通知權限根本不沾邊的應用,想想還是算了吧。
以多種方式相互喚醒、相互拉活,是目前最穩定、最安全的做法,各大做得好一點的應用都有類似行為。當然,對於很多小應用來說,依然可以使用一些第三方網絡服務,比如 XX 推送:一旦設備上的某個應用透過 XX 的推送獲得訊息時,是可以間接喚醒其他應用並推送與其相關的訊息的,前提是某推送服務也做了保活措施。
從零開始搭建 Android 開發環境:JDK、SDK、ADT 與 AVD 完整流程
要開始寫 Android 程式,第一道門檻就是把開發環境搭起來。整個過程大致可以拆成四個階段:確認 JDK、下載 SDK、安裝 ADT、建立 AVD(Android 虛擬
Android TV 開發入門(一):打造 TV App 前必備的知識
前言:近年來智慧電視發展得如火如荼,Google 也在大力推進 TV 及穿戴設備的布局。站在互聯網的風口上,那句「站在風口,豬都能飛」的調侃並非毫無道理。如今,傳統電視機
Windows 下 Android 開發環境搭建與配置圖解教學
網上關於 Windows 下搭建 Android 開發環境的文章不勝枚舉,為方便日後參考,這裡做個記錄,重點關注安裝過程中的注意事項。本文介紹的是面向 Java 的 SD
Android 手機無法連接無線網路的解決辦法大全
Android 手機連不上 Wi-Fi,是許多使用者都碰過的困擾。問題可能出在手機端、路由器端,或是 IP 設定上。以下依三種常見情境,整理了完整的排查思路。 一、手機