I have gone through many a documentation to understand how to keep the notification of a foreground service even after the service is stopped.
I have followed the steps suggested by the accepted answer here: Keeping notification from dismissing when service is destroyed in Oreo
My code is as follows:
public void onDestroy() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
stopForeground(Service.STOP_FOREGROUND_DETACH);
} else {
stopForeground(false);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = gpsServiceNotificationSingleton.getNotificationBuilder().build();
mNotificationManager.notify(MYMConstants.FOREGROUND_ID_FOR_NOTIFICATION, notification);
}
}
The issue here is, even after passing STOP_FOREGROUND_DETACH flag to stopForeground, I am unable to keep the notification as the notification is cleared. Am I missing something here?
After a lot of trials and errors, I have found out that adding stopForeground(Service.STOP_FOREGROUND_DETACH) into the scope of onDestroy() will clear the generated notification no matter what.
In order to keep the notification even after the corresponding foreground service is killed, one must call stopForeground(Service.STOP_FOREGROUND_DETACH) outside of onDestroy(). An example of this would be:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if(intent.getAction().equals("STOP_SERVICE_ACTION")) {
// your code
} else if(intent.getAction().equals("START_SERVICE_ACTION")) {
// your code
}
return START_STICKY;
}