I use startForeground
to make my service persistent. Thus, I must build a notification to pass it to the startForeground
function.
I want to start that foreground service without letting the notification make an alert (i.e. with vibration or sound).
For android 8 devices, I create a notification channel before calling the startForeground
. I set the importance to NotificationManager.IMPORTANCE_NONE
to avoid notification alerts (just to make the icon appear on the status bar).
However, on some devices, I still have a notification alert (for Samsung Galaxy S8 and Honor View 10).
So, I tested this approved answer https://stackoverflow.com/a/24008765/10069542.
This worked fine for the Samsung Galaxy S8. Nonetheless, the Honor View 10 still emits an alert when I start my foreground service.
Here is the code to create my notification channel and to build the notification to be passed to startForeground
Notification channel
@RequiresApi(api = Build.VERSION_CODES.O)
private String createNotificationChannel() {
String channelId = NOTIFICATION_CHANNEL_ID;
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (service != null) {
service.createNotificationChannel(chan);
} else {
Log.e(TAG, "Error creating notification channel");
return null;
}
return channelId;
}
Notification
private Notification getNotification() {
Intent startIntent = new Intent(getApplicationContext(), RangoActivity.class);
startIntent.setAction(Intent.ACTION_MAIN);
startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
this, REQ_CODE_REQUEST_RANGO_SERVICE, startIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID);
} else {
builder = new Notification.Builder(this);
}
builder.setSmallIcon(R.drawable.rango_notification_icon)
.setContentTitle(getString(R.string.notification_content_title))
.setContentText(getString(R.string.notification_content_text))
.setTicker(getString(R.string.notification_ticker))
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
.setVibrate(new long[]{0L})
.setWhen(System.currentTimeMillis())
.setOngoing(true)
.setAutoCancel(true)
.setContentIntent(contentIntent);
Notification notification = builder.build();
return notification;
}