简体   繁体   中英

Android app closes when cleared from the running app list. How to make it restart

I want to restart my app when it is cleared from the running apps list. How do i do so? this is the incomplete code for my service

public class MyService extends Service {

Handler handler = new Handler();
final double specifiedlimit=0.001;
int f = 0;

@Override
public void onCreate() {
    super.onCreate();
}


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

    final long intervalTime = 10000; // 5 mins
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            gpstracker();
            handler.postDelayed(this, intervalTime);
        }
    }, intervalTime);

    return START_STICKY;

}

Implement onTaskRemoved() in your service.

 @Override
public void onTaskRemoved(Intent rootIntent) {
    Log.e("Service", "On task removed");
    Intent restartService = new Intent(getApplicationContext(), this.getClass());
    restartService.setPackage(getPackageName());
    PendingIntent restartServicePI = PendingIntent.getService(
            this, 1, restartService,
            PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM