萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android Service 常駐與自動重啟策略:監聽螢幕解鎖廣播實現死後重生

Service 存活面臨的挑戰

  • 使用者手動停止(設定 → 應用程式 → 強制停止)。
  • 系統記憶體不足殺死背景進程(Low Memory Killer)。
  • 第三方清理工具(360、安全管家等)一鍵清理。
  • Android 8.0+ 背景執行限制(前台 Service + 通知通道)。

常見重啟方案比較

方案原理優點缺點
START_STICKY系統記憶體允許時自動重建簡單不保證立即重啟,Intent 為 null
AlarmManager 定時拉活定時發送廣播啟動 Service可控間隔Doze 模式限制、耗電、Android 12+ 精確鬧鐘需權限
JobScheduler / WorkManager系統排程框架系統級優化、電量友善非即時、有最小間隔限制(15 分鐘)
監聽系統高頻廣播接收 BOOT_COMPLETED、USER_PRESENT 等即時、無額外排程、系統保證送達需聲明權限、部分廣播受限

核心技巧:監聽 USER_PRESENT(螢幕解鎖)

觀察發現:多款長存活 App(如導航、即時通訊)在清理後,使用者解鎖螢幕瞬間自動重啟。關鍵廣播:

  • android.intent.action.USER_PRESENT:使用者解鎖螢幕(含開機解鎖)。
  • android.intent.action.BOOT_COMPLETED:開機完成(需 RECEIVE_BOOT_COMPLETED 權限)。

Manifest 註冊



    
        
    


    
        
        
    

Receiver 實作啟動 Service


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+
    }
}

前台 Service 強制存活

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;
    }
}

綜合防殺策略

  1. Service 返回 START_STICKY。
  2. 啟動為前台 Service(顯示低優先級通知)。
  3. 註冊 BOOT_COMPLETED + USER_PRESENT 廣播啟動 Service。
  4. 使用 WorkManager 週期性檢查 Service 存活,若死則重啟(作為雙重保險)。
  5. 引導使用者加入電池優化白名單、鎖定應用(部分廠商 ROM 支援)。

結合系統廣播與前台 Service,最大程度保障長連線、定位、推送等核心服務持續運行。

copyright © 萬盛學電腦網 all rights reserved