Before indicating this post as a duplicate, please look at the complete description. I have been looking everywhere and cannot seem to find the solution to my problem.
The problem In my application, notifications don't show up on Android 8 or higher. I cannot seem to get any notification to show up at all.
What did I try so far?
I looked at this post, this post, a couple of tutorials like this one.
All talk about setting the smallIcon, contentTitle, contentText and a notification channel. I did all of this, but without any apparent success.
My code
In my NotificationHelper class I have the following methods:
public NotificationHelper(Context base) {
super(base);
createChannels();
}
public void createChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Android 8 or higher? Set notification channel
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
getManager().createNotificationChannel(notificationChannel);
}
}
private NotificationManager getManager() {
if (notifyManager == null) {
notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
return notifyManager;
}
public Notification getNotification1(Context context) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ONE_ID)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notification_alert); // alert icon.
return builder.build();
}
public void notify(int id, Notification notification) {
Log.i("NotificationHelper", "Notifying with notification: " + notification.toString());
getManager().notify(id, notification);
}
And then in my MainActivity I have the following method in an onButtonClick event (obviously after instantiating the notificationHelper object in the MainActivity's onCreate() method):
Notification notification = notificationHelper.getNotification1(this);
notificationHelper.notify(NotificationHelper.notification_one, notification);
Does anyone have any ideas?
EDIT: It turns out the code works fine when run on an emulator. It could be a problem with the battery optimization settings, as specified here.