SoFunction
Updated on 2025-04-10

Sample code for basic usage of Android notifications

When writing Android notifications, I found that the Notification setLatestEventInfo was deprecated, so I searched and sorted out the basic usage of new Android notifications.

1. Get NotificationManager instance

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

2. Create Notification instance

Here you need to select the implementation method according to the project's min-sdk. For MIN API Level < 11, you can use the setLatestEventInfo() method. The following introduces the Notification instance acquisition method after API Level 11.

1. MIN API Level < 16 Methods to build Notification instances

1) Create an instance

       builder = new (context) 
      .setAutoCancel(true) //Set the notification automatically cancels after clicking notification      .setContentTitle("title") //Notification title      .setContentText("describe") //Notify the content of the second line      .setContentIntent(pendingIntent) //After clicking the notification, send the specified PendingIntent      .setSmallIcon(.ic_launcher); //Notification icon,Must set otherwise notifications will not be displayed

2) The getNotification() method called obtain Notification

                     notification = ();

2. MIN API Level >=16 Methods to build Notification instances

            Notification notification = new (context)
            .setAutoCancel(true)
            .setContentTitle("title")
            .setContentText("text")
            .setSmallIcon(.ic_launcher)
            .setContentIntent(pendingIntent)
            .build();

3. Send notifications

                          (1,notification);

The above is a compilation of the knowledge and information on the Android notification column. We will continue to add it later. Thank you for your support for this site.