*Creating a notification*
- To create: - call `Notification.Builder.build()`, which returns a Notification object containing your specifications - issue the notification by calling `notify()` (passes the Notification object to the system)
- A Notification object must contain: - A small icon, set by `setSmallIcon()` - A title, set by `setContentTitle()` - Detail text, set by `setContentText()` - A valid notification channel ID, set by `setChannelId()` - If you target Android O and post a notification without specifying a valid notifications channel, the notification fails to post and the system logs an error. - Note: You can turn on a new setting in Android O to display an on-screen warning that appears as a toast when an app targeting Android O attempts to post without a notification channel. To turn on the setting for a development device running Android O, navigate to Settings > Developer options and toggle Show notification channel warnings to on.
- Code example (code associates the notification with a notification channel using the channel’s ID):
```java {code} mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated. int notifyID = 1;
// The id of the channel. String CHANNEL_ID = "my_channel_01";
// Create a notification and set the notification channel. Notification notification = new Notification.Builder(MainActivity.this) .setContentTitle("New Message") .setContentText("You've received new messages.") .setSmallIcon(R.drawable.ic_notify_status) .setChannelId(CHANNEL_ID) .build();
// Issue the notification. mNotificationManager.notify(id, notification); ``` {code}
_*Reading notification channel settings*_
- Users can modify the settings for notification channels, including behaviors such as vibration and alert sound. You can discover the settings a user has applied to a notification channel by the following:
- To retrieve a single notification channel, you can call `getNotificationChannel()`.
```java {code} NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); NotificationChannel notificationChannel = notificationManager.getNotificationChannel("some_id"); ``` {code}
- To retrieve all notification channels belonging to your app, you can call `getNotificationChannels()`.
```java {code} NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); List<NotificationChannel> notificationChannels = notificationManager.getNotificationChannels(); ``` {code} |
|