I created a sticky Foreground service which restarts every-time it gets killed, it seems to work fine but I noticed that in some cases ( when the OS kills it) it just wont restart. How can I make it restart EVERY time it gets killed? I want this service to run always.

Like those services.
This is my Foreground service onStartCommand:
public int onStartCommand(Intent intent, int flags, int startId) {
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("InsiteMobile Service")
            .setContentText("Run the app by clicking here")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pendingIntent)
            .build();
    Log.i("InsiteMobileLog", "Service Started");
    startForeground(1, notification);
    //do heavy work on a background thread
    //stopSelf();
    return START_STICKY;
}
And this is how i call the service in MainActivity onCreate():
public void startService() {
    Intent serviceIntent = new Intent(this, AppService.class);
    serviceIntent.putExtra("inputExtra", "InsiteMobileService");
    ContextCompat.startForegroundService(this, serviceIntent);
}
Currently I am working on same project where I need services to be running in background. There are several things that we need to care about
1. In onDestroy() method of service, start itself again using startService Intent
2.For OS with and below kitkat use onTaskRemoved(intent); in onStartCommand() method
3. Return START_STICKY in onStartCommand()
And after this, you need to understand one more thing, phone manager of the device tends to kill the background processes based on battery optimization policies. Check for the phone manager settings of your testing device and then try again.
Also, if you are going use notification to keep the service alive, you need to recheck the permission for sending notification through your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With