1. Set notification content
//CHANNEL_ID, channel ID, Android 8.0 and higher must be set builder = new (this, CHANNEL_ID) //Set small icon .setSmallIcon(.notification_icon) //Set the title .setContentTitle(textTitle) //Set content .setContentText(textContent) //Set level .setPriority(NotificationCompat.PRIORITY_DEFAULT);
2. Create a channel
Provide notifications on Android 8.0 and later, and notification channels for the application are required to register in the system.
private void createNotificationChannel() { if (.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(.channel_name); String description = getString(.channel_description); // Different degrees of importance will affect the way notifications are displayed int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); (description); NotificationManager notificationManager = getSystemService(); (channel); } }
The above code should be executed immediately upon application startup and can be initialized in Application.
3. Set the click operation of the notification bar
Generally, clicking the notification bar will open the corresponding Activity interface. The specific code is as follows:
//The interface you want to open when clicking Intent intent = new Intent(this, ); //Generally, click notifications open an independent interface. In order to avoid adding to the existing activity stack, you can set the following startup method (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); //Create a pendingIntent of activity type, and you can also create other components such as broadcasts. PendingIntent pendingIntent = (this, 0, intent, 0); builder = new (this, CHANNEL_ID) .setSmallIcon(.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) //Set pendingIntent .setContentIntent(pendingIntent) //Set whether it disappears automatically after clicking .setAutoCancel(true);
4. Display notification
NotificationManagerCompat notificationManager = (this); //NotificationId is equivalent to the unique identifier of the notification, used to update or remove notifications (notificationId, ());
There are many special features that can be viewed directlyOfficial website tutorialMake settings.
The above is the detailed content of how to use the Android notification bar. For more information about using the Android notification bar, please follow my other related articles!