Notifications
Notifications are an important part of many Android applications, as they allow the application to provide updates and alerts to the user even when the application is not in the foreground. Android provides several classes and interfaces to handle notifications, including NotificationManager, NotificationCompat, and PendingIntent.
Here's an example of how to create and display a notification using NotificationCompat:
java
// Create a notification builder
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My Notification")
.setContentText("This is a notification message.")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
// Get the notification manager
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// Display the notification
notificationManager.notify(notificationId, builder.build());
In the above example, we create a NotificationCompat.Builder object and set various attributes for the notification, such as the small icon, title, and text. We also set a content intent using a PendingIntent object, which will be triggered when the user taps on the notification. Finally, we get a NotificationManagerCompat object and use it to display the notification using the notify method.
No comments:
Post a Comment