簡體   English   中英

android中的服務沒有重啟

[英]Service in android is not restarting

我在android中使用服務來完成某些任務,我希望每次都能運行我的服務。 但是當我清除Android手機的內存時,我的服務被殺死而沒有重啟。 我讀過幾篇文章,建議START_STICKY解決問題但不會發生。

下面是我在服務中的onStartCommand代碼,我將返回START_STICKY 即使onDestroy在這種情況下也沒有被調用。

public int onStartCommand(Intent intent, int flags, int start_Id) {
    return START_STICKY;
}

一旦強制停止,嘗試使用此功能重新啟動服務。

注意:如果您還要從其他地方停止此服務,那么它也將再次重新啟動服務,因此您必須檢查此功能,即停止服務或強制停止服務。 如果您自己停止服務,則在共享首選項中保存服務狀態停止類型[非強制],並使用該狀態檢查不再啟動它。

@Override
    public void onTaskRemoved(Intent rootIntent){
        Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
        restartServiceIntent.setPackage(getPackageName());

        PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(
                AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime() + 5000,
                restartServicePendingIntent);

        super.onTaskRemoved(rootIntent);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM