CL So
CL So

Reputation: 3759

How to reduce Android service restart time?

I know Android service will restart if I return START_REDELIVER_INTENT in onStartCommand

I wrote a service and want to keep it alive after user close the app in recent list

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

    return START_REDELIVER_INTENT;
}

After my testing, my service will be killed if user close the app in recent list

Since the START_REDELIVER_INTENT, Android will auto restart the service, but the time is too long

Some time the service will restart within 20 seconds, some time will restart over one minute, how can I reduce this time? it is better within 5 seconds.

Upvotes: 1

Views: 406

Answers (1)

Divyesh Patel
Divyesh Patel

Reputation: 2576

Use this code inside of your Service class. This restart service when app is cleared by user. And you can return START_STICKY to onstartCommand method.

@Override
    public void onTaskRemoved(Intent rootIntent) {
        Intent intent2 = new Intent(this.getApplicationContext(), this.getClass());
        intent2.setPackage(this.getPackageName());
        PendingIntent pendingIntent = PendingIntent.getService((Context)this.getApplicationContext(), (int)1, (Intent)intent2,0);
        ((AlarmManager)this.getApplicationContext().getSystemService(ALARM_SERVICE)).set(3, 500 + SystemClock.elapsedRealtime(), pendingIntent);
        super.onTaskRemoved(rootIntent);
    }

Upvotes: 1

Related Questions