Notification code for android 12 and above :
If your app targets Android 12, you must specify the mutability of each PendingIntent object that your app creates. This additional requirement improves your app's security.
Before ANDROID 12
PendingIntent contentIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
For ANDROID 12 :
PendingIntent contentIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Create channel first :
@RequiresApi(api = Build.VERSION_CODES.O)
private synchronized String createChannel() {
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
String name = "dummy text for channel";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel("channel name, name, importance);
mChannel.setShowBadge(false);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
} else {
stopSelf();
}
return "Channel";
}
Notification Example :
String channel="";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
channel = createChannel();
else {
channel = "";
}
RemoteViews mContentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.general_notification_layout_new);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channel);
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
builder.setSmallIcon(R.drawable.notification_small_icon_one)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(notificationSound)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setCustomContentView(mContentView)
.setCustomBigContentView(mContentView)
.setContentIntent(contentIntent);
builder.setAutoCancel(true);
Notification notification = builder.build();
mNotificationManager.notify(notificationId, notification);
Context context = getApplicationContext();
beforeNotification notification = new Notification(icon, tickerText, when);
maybe you are not passing right context for starting Activity – Tricycle