Because of the notifications vary by the Android version, it is recommended to use the Notification compatibility class. Use the Notification Builder, and set the notifications settings with the set methods. The build method will create the instance, but to display a notification you need the NotificationManager which is called with getSystemService method.
Create a notification
ChannelId is a string that is used the channel that the notification will be assigned. You choose the id. setDefault specifies the notification defaults (light, vibration etc). setSmallIcon specifies the small icon that will appear at the top bar.
Now the NotificatioManager:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
From Android 8.0 all the notifications should be assigned to a channel. And from there you can configure them all together. For that reason, you have to create a NotificationChannel, and only for Android 8.0 or later.
To show the notification you have to use the notify method
mNotificationManager.notify(0 , mBuilder.build());
You can change the style of the notification with setStyle(). There are 3 styles you can choose from:
- BigTextStyle that has more text and expands only when is the top of the notifications
- BitePictureStyle that has a bigger picture
- InboxStyle that has a list with 5 items.
if you want to open an activity, start a service etc, you need to use setContentIntent() that accepts a PendingIntent. PendingIntent wraps an intent launching an activity with its extras and pass it outside the app boundaries.
You can put extra actions below the notification using addAction() and passing a PendingIntent.
- Android – Notifications
- Content Provider – Part 3 – insert, delete, update, getType
- Content Provider – Part 2 – create and query