I'm trying to make a sticky service, which restarts itself after a short time after dying (for example, because Android has killed it to free the memory). (Un)fortunately I'm on Android 5.0.1 which has a beautiful bug of memory leak and makes real testing easy.
Looking at logcat
I see:
I/ActivityManager( 943): Process com.app.my (pid 28834) has died
W/ActivityManager( 943): Scheduling restart of crashed service com.app.my/com.service.my in 191688ms
I/ActivityManager( 943): Process com.app.my (pid 30842) has died
W/ActivityManager( 943): Scheduling restart of crashed service com.app.my/com.service.my in 766752ms
later the time is rising to 3M making it inacceptable.
I've tried to fix that using AlarmManager and restart intent:
Intent restartIntent = new Intent(activity, activity.getClass());
restartIntent.putExtra("config", config);
PendingIntent restartAct = PendingIntent.getActivity(
activity.getApplicationContext(), 0, restartIntent, PendingIntent.FLAG_NO_CREATE);
AlarmManager alarmManager = (AlarmManager)activity.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 60000, 60000, restartAct);
However this didn't help. I can't find any information in log, so maybe AlarmManager repeating is abandoned after activity has died or perhaps I've done something incorrectly?
I was observing WhatsApp application and I've found:
I/ActivityManager( 943): Process com.whatsapp (pid 27009) has died
W/ActivityManager( 943): Scheduling restart of crashed service com.whatsapp/.messaging.MessageService in 10947ms
I/ActivityManager( 943): Process com.whatsapp (pid 29913) has died
W/ActivityManager( 943): Scheduling restart of crashed service com.whatsapp/.messaging.MessageService in 10918ms
I/ActivityManager( 943): Process com.whatsapp (pid 30681) has died
W/ActivityManager( 943): Scheduling restart of crashed service com.whatsapp/.messaging.MessageService in 10987ms
The first and the last crash was exactly at the same time as com.app.my process. Somehow WhatsApp manages to keep the "retry time" at the same level despite frequent crashes. How does they do that? The answer here suggests it should be the same for all aps: Crashed service restarted after a very long time
Remarks:
- the service returns START_REDELIVER_INTENT
- using onDestroy to start the activity/service again isn't a solution because it is not called in that case.
- I'm also not trying to restart after forced stop (Restart service after force stop)
- I've tried doing "busy work" in onCreate. That didn't help to cut the restart times (Time taken for Android Service to restart after being forcibly killed)
- I'm not starting a thread but an activity, so this is irrevelant in my case, right? Android: Scheduling restart of crashed service with HUGE delay?
- I'm can't use notification, so START_STICKY, foreground Android service goes away without notice is not a solution