| 方案 | 原理 | 優點 | 缺點 |
|---|---|---|---|
| START_STICKY | 系統記憶體允許時自動重建 | 簡單 | 不保證立即重啟,Intent 為 null |
| AlarmManager 定時拉活 | 定時發送廣播啟動 Service | 可控間隔 | Doze 模式限制、耗電、Android 12+ 精確鬧鐘需權限 |
| JobScheduler / WorkManager | 系統排程框架 | 系統級優化、電量友善 | 非即時、有最小間隔限制(15 分鐘) |
| 監聽系統高頻廣播 | 接收 BOOT_COMPLETED、USER_PRESENT 等 | 即時、無額外排程、系統保證送達 | 需聲明權限、部分廣播受限 |
觀察發現:多款長存活 App(如導航、即時通訊)在清理後,使用者解鎖螢幕瞬間自動重啟。關鍵廣播:
android.intent.action.USER_PRESENT:使用者解鎖螢幕(含開機解鎖)。android.intent.action.BOOT_COMPLETED:開機完成(需 RECEIVE_BOOT_COMPLETED 權限)。
public class UserPresentReceiver extends BroadcastReceiver {
private static final String TAG = "UserPresentReceiver";
@Override public void onReceive(Context context, Intent intent) {
Log.e(TAG, "receive USER_PRESENT, restart service");
Intent service = new Intent(context, MyLongRunningService.class);
ContextCompat.startForegroundService(context, service); // Android 8.0+
}
}
Android 8.0+ 要求長時間運行 Service 必須為前台 Service:
public class MyLongRunningService extends Service {
private static final int NOTIFICATION_ID = 1;
private static final String CHANNEL_ID = "foreground_channel";
@Override public void onCreate() {
super.onCreate();
createNotificationChannel();
startForeground(NOTIFICATION_ID, buildNotification());
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "前台服務", NotificationManager.IMPORTANCE_LOW);
NotificationManager mgr = getSystemService(NotificationManager.class);
mgr.createNotificationChannel(channel);
}
}
private Notification buildNotification() {
return new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("服務運行中")
.setContentText("點擊打開應用")
.setSmallIcon(R.drawable.ic_notification)
.setPriority(NotificationCompat.PRIORITY_LOW)
.build();
}
@Override public int onStartCommand(Intent intent, int flags, int startId) {
// 核心業務邏輯
return START_STICKY;
}
}
START_STICKY。BOOT_COMPLETED + USER_PRESENT 廣播啟動 Service。WorkManager 週期性檢查 Service 存活,若死則重啟(作為雙重保險)。結合系統廣播與前台 Service,最大程度保障長連線、定位、推送等核心服務持續運行。