Android – Notifications

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

Create notifications, <span>Android – Notifications</span>, KandZ

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.

Create notifications, <span>Android – Notifications</span>, KandZ

To show the notification you have to use the notify method

mNotificationManager.notify(0 , mBuilder.build());

styles

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.
Create notifications, <span>Android – Notifications</span>, KandZ

default action

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.

Create notifications, <span>Android – Notifications</span>, KandZ

extra actions

You can put extra actions below the notification using addAction() and passing a PendingIntent.

Create notifications, <span>Android – Notifications</span>, KandZ

THE END!!!

100070cookie-checkAndroid – NotificationsAndroid – Notifications

Related posts