I have seen many tutorials saying that to do this I have to use a service. After watching a youtube video, got this:
public class MyService extends Service {
public MyService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onTaskRemoved(intent);
Toast.makeText(this, "Service", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
startService(restartServiceIntent);
super.onTaskRemoved(rootIntent);
}
}
And I have to call this service in MainActivity using startService(new Intent(this, MyService.class));
This is working fine. Even if I close the app from the Recent Apps. But when I Force Stop the app from Settings, the service doesn't work anymore.
Is there any way to keep the app running even if the app is forcibly killed?