android 12 及更高版本的通知代码:
如果您的应用面向 Android 12,则必须指定应用创建的每个 PendingIntent 对象的可变性。此附加要求可提高您应用的安全性。
ANDROID 12 之前
PendingIntent contentIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
对于安卓 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);