0

創建了IntentService並將for loop放入onHandleIntent方法中。每當我關閉應用程序(從最近不強制關閉),它停止。但onDestroy沒有叫。 我也嘗試過不同的設備。我不認爲這是一個內存不足的問題。
服務的意思是隻有當應用程序在前臺使用?
我必須在主線程的背景中執行一些任務,並且在用戶關閉應用程序時服務已關閉。
這裏是我的示例代碼Android服務在關閉應用程序後立即停止

public class MyIntentService extends IntentService { 


    private static final String TAG = "MyIntentService"; 

    public MyIntentService() { 
     super("MyIntentService"); 
    } 


    @Override 
    protected void onHandleIntent(Intent intent) { 

     for (int i = 0; i < 30; i++) { 
      Log.d(TAG, "onHandleIntent: " + i); 
      try { 
       Thread.sleep(600); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 


    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     Log.d(TAG, "onDestroy: "); 
    } 
} 

裁判:How to keep an IntentService running even when app is closed?
Service restarted on Application Close - START_STICKY

回答

1

使用下面的重啓服務代碼上述方法關閉App

public class MyService extends Service { 

@Override 
public int onStartCommand(final Intent intent, final int flags, 
          final int startId) { 
    super.onStartCommand(intent, flags, startId); 
    return Service.START_STICKY; 
} 

@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public void onTaskRemoved(Intent rootIntent) { 
    Intent restartService = new Intent(getApplicationContext(), 
      this.getClass()); 
    restartService.setPackage(getPackageName()); 
    PendingIntent restartServicePI = PendingIntent.getService(
      getApplicationContext(), 1, restartService, 
      PendingIntent.FLAG_ONE_SHOT); 
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); 
    alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 100, restartServicePI); 
    Toast.makeText(this, "onTaskRemoved", Toast.LENGTH_SHORT).show(); 
    super.onTaskRemoved(rootIntent); 
}} 

後100毫秒後onTaskRemoved重新啓動服務。

+0

爲什麼我應該使用onTaskRemoved。除非記憶力下降,否則服務不應該被殺死。根據Android文檔,這是默認功能。 –

0
@Override 
    public void onTaskRemoved(Intent rootIntent) { 
} 

上述方法將在應用程序從最近刪除時調用。但是沒有上下文。所以你需要在上下文可用時完成你的任務。因此,地方的代碼裏面,

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 

    //do your operations 
    return START_REDELIVER_INTENT; 
} 

記住裏面onStartCommand你應該返回要麼START_REDELIVER_INTENT或START_STICKY。你可以得到不同的結果from here.

還有一件事,只有在代碼的任何地方調用startService時,onStartCommand纔會自動撤銷。

所以,通過調用

startService(new Intent(context, serviceName.class));

按照上面的代碼onStartCommand如果服務沒有停止將定期撤銷運行服務。

+0

爲什麼我應該使用onTaskRemoved。除非記憶力下降,否則服務不應該被殺死。根據Android文檔,這是默認功能。 –

+0

這裏是一個解釋 - https://stackoverflow.com/questions/20392139/close-the-service-when-remove-the-app-via-swipe-in​​-android?rq=1 – Exigente05

相關問題