I know this question is asked so many times but i didn't find any solution to keep service alive even if my app get killed. My application run on all devices but some devices if i kill the app then my service also killed (Device name MI 4 Version ans asus 5.0.3 )
following is my service code where i have started my foreground service
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("My service started at ")
.setTicker("My service started")
.setContentText("app")
.setSmallIcon(R.drawable.app)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true).build();
startForeground(Constants.FOREGROUND_SERVICE,notification);
}
For this problem, i make many checkpoints for my TestService on various events i.e.
Then i have a class called ServiceDetector.java
Which checks if my service is running, Now if your service is not running then start it again
One workaround you can implement is to restart the service whenever it is removed. ie, using onTaskRemoved callback (link).