Android 12及以上版本的通知代码:
如果你的应用程序的目标是Android 12,你必须指定每个 PendingIntent 对象的可变性。这个额外的要求可以提高你的应用程序的安全性。
在 Android 12 之前:
PendingIntent contentIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
对于 Android 12:
PendingIntent contentIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
首先创建频道:
@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";
}
通知示例:
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);
![Android 12 notifications](https://istack.dev59.com/NsMFq.webp)
Context context = getApplicationContext();
移动到Notification notification = new Notification(icon, tickerText, when);
之前,也许您没有传递正确的上下文来启动 Activity。 - ρяσѕρєя K