Create Notification on Android in Java

To create a notification on Android in Java, you can use the NotificationCompat.Builder class and its setContentTitle(), setContentText(), and setSmallIcon() methods to set the title, text, and icon for the notification, respectively. You can then use the getNotification() method to retrieve the notification object, and the notify() method of the NotificationManager class to post the notification.

Here is an example of how you could create and post a notification in Java on Android:

// Create the NotificationCompat.Builder object
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
        .setContentTitle("Notification Title")
        .setContentText("This is the notification text.")
        .setSmallIcon(R.drawable.notification_icon);

// Get the Notification object
Notification notification = builder.build();

// Get the NotificationManager and post the notification
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, notification);

This code will create a notification with the specified title and text, and using the icon specified by the notification_icon drawable resource. When the notification is posted, it will be assigned the ID specified by the NOTIFICATION_ID constant.

Spread the love

Leave a comment