Android system can stop your service anytime when they want to stop to maintain the device performance or power consumption. There are many situation where android system can stop your service like low battery, app is not in active state for a long time, device is in sleeping mode, power saving mode etc.
I developed a trick or hack(you can say that) by using that no one can stop your service (Android System, Third Party apps, User).
Note: By using this your service will never stop and may drain your battery also.
Follow the steps below :-
1) Return START_STICKY in onStartCommand.
2) Then modify the onDestroy() and onTaskRemoved() method in your service as below:
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "Service Task destroyed", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(getApplicationContext(), YourService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, myIntent, 0);
AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(getApplicationContext(), "Start Alarm", Toast.LENGTH_SHORT).show();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent myIntent = new Intent(getApplicationContext(), YourService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, myIntent, 0);
AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(getApplicationContext(), "Start Alarm", Toast.LENGTH_SHORT).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Service Starts", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
Here i am setting an alarm every time whenever the service is stop (by android system or by user mannually) and using PendindIntent restart the service within 10 seconds every time.