Override onTaskRemoved () in your service and use the alarm manager to start the service again. Below is the code for our application that does the same and works great:
@Override public void onTaskRemoved(Intent rootIntent) { super.onTaskRemoved(rootIntent); Log.d(TAG, "TASK REMOVED"); PendingIntent service = PendingIntent.getService( getApplicationContext(), 1001, new Intent(getApplicationContext(), MyService.class), PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service); }
As you can periodically send a location even if the service was killed in low memory (or for some reason), I suggest you handle the uncaughtException to restart it after N seconds. Here's how we did it in our application, which works great:
private Thread.UncaughtExceptionHandler defaultUEH; private Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { Log.d(TAG, "Uncaught exception start!"); ex.printStackTrace();
Note: I THINK and I remember that I checked it in Kitkat that START_STICKY does not work on Kitkat levels and above the API. Please confirm this yourself.
MORE:
Since you periodically send local dispatches, you might have to consider deep sleep mode. To make things work in deep sleep, use the WakefulBroadcastReceiver in combination with the AlarmManager. Take a look at my other post How to use http in deep sleep mode .
UPDATE:
This solution does not work (in fact, it doesnβt need to work) if the user "FORCE STOP" the application from "Settings". This is actually good, since restarting the service is not a good way if the user himself wants to stop the application. So this is normal.
source share