I have a Chat application which runs in background also, so when I kill my application in any way be it swiping out of the recent app or killing the app inside setting, I want my Service to restart everytime and it should be awake all time untill the application is running. I have tried Broadcast Receiver to restart my service.
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyService", "onDestroy");
sendBroadcast(new Intent("RestartService"));
}
And I have also tried onTaskRemoved
@Override
public void onTaskRemoved(Intent rootIntent) {
Log.d(TAG, "onTaskRemoved:");
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
and also in startCommand I have user START_STICKY, but nothing seems to work. Any help on this would be appreciated..