Create Notification Alert - Android Example

 

Create Notification Alert - Android Example



In This example creating Notification Alerts with the use of NotificationManager.

 

Some times we have requirement to show alert user from background services or from broadcast reciever then best way to notify user by Notification Alert

 

File : src/NotificationAlert.java

 

Create notification alert to user.

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />


package com.example.camera3;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

public class notification extends AppCompatActivity {

private String channelId = "my_channel";
private NotificationManager notifManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);

// createNotificationChannel();
showNotification();
}

// private void createNotificationChannel() {
// String channelName = "Custom notification channel";
// int importance = NotificationManager.IMPORTANCE_HIGH;
//
// NotificationChannel notifChannel = new NotificationChannel(channelId, channelName, importance);
//
// notifManager = getSystemService(NotificationManager.class);
// notifManager.createNotificationChannel(notifChannel);
// }

private void showNotification() {
int notificationId = 1;
final int NOTIFY_ME_ID=1337;
/*********** Create notification channel ***********/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "MyChannel", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
/*********** Create notification ***********/
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Android Example Notification Title")
.setContentText("This is the android example notification message")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true);

// This pending intent will open after notification click
Intent intent = new Intent(this, notification.class);
PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(this, notification.class), PendingIntent.FLAG_IMMUTABLE);

builder.setContentIntent(i);

NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(NOTIFY_ME_ID, builder.build());
}


}

 

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.