My goal is for the user to be able to swipe an app away and shut down a foreground service. I do this by overriding onTaskRemoved. This works as expected, and I shut down my service from the method, but now there is the issue of the system shutting down the foreground service using onTaskRemoved.
Forget what setting I used, but my app is listed as exempt in the standby apps.
What can I do to stop the system from shutting down my foreground service?
I do what the developers guide says and more.
Intent intentServiceMain = new Intent(ActivityMain.this, ServiceMain.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intentServiceMain);
} else {
startService(intentServiceMain);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Service starting", Toast.LENGTH_SHORT).show();
setUpNotificationBuilder();
notification = notificationCompatBuilder.build();
startForeground(NOTIFICATION_CHANNEL_ID.hashCode(), notification);
return START_STICKY;
}
private void setUpNotificationBuilder() {
notificationCompatBuilder = new NotificationCompat.Builder(
getApplicationContext(), NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.music_note_black_48dp)
.setContentTitle(NOTIFICATION_CHANNEL_ID)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle());
remoteViewsNotificationLayout =
new RemoteViews(getPackageName(), R.layout.pane_notification);
notificationCompatBuilder.setCustomContentView(remoteViewsNotificationLayout);
Intent notificationIntent = new Intent(getApplicationContext(), ActivityMain.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, notificationIntent, 0);
notificationCompatBuilder.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_ID, importance);
String description = "Service";
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}