Junior
How to create a notification in Android?
sobes.tech AI
Answer from AI
To create a notification in Android, follow these steps:
- Create a notification channel (for API level 26 and above).
- Build the notification using
NotificationCompat.Builder. - Display the notification through the notification manager.
// Creating a notification channel (API 26+)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "my_channel_id";
CharSequence channelName = "My Channel";
String channelDescription = "Description for My Channel";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
channel.setDescription(channelDescription);
// Register the channel with the system
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
// Building the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "my_channel_id") // Specify the channel ID
.setSmallIcon(R.drawable.ic_notification) // Notification icon
.setContentTitle("Notification Title") // Title
.setContentText("Notification text") // Text
.setPriority(NotificationCompat.PRIORITY_DEFAULT); // Priority
// Creating a PendingIntent for the action when clicking the notification
// For example, opening an activity
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); // Flag for API S+
builder.setContentIntent(pendingIntent);
// Display the notification
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
int notificationId = 1; // Unique ID for the notification
notificationManagerCompat.notify(notificationId, builder.build());
Main components of a notification:
- Small icon:
setSmallIcon(), displayed in the status bar. - Title:
setContentTitle(), the main text of the notification. - Text:
setContentText(), additional text. - Notification channel (API 26+): A group of notifications with shared settings.
- PendingIntent: Action performed when clicking the notification.
Additionally, you can add a large image (setStyle(new NotificationCompat.BigPictureStyle())), action buttons (addAction()), and customize sound, vibration, and other parameters.