要解决Android 7.1及以下版本中重复显示通知的问题,可以使用以下代码示例:
// 创建一个唯一的通知ID
int notificationId = 1;
// 创建一个通知构建器
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("标题")
.setContentText("内容")
.setAutoCancel(true);
// 创建一个Intent,用于点击通知时打开一个Activity
Intent intent = new Intent(context, YourActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// 设置点击通知时的动作
builder.setContentIntent(pendingIntent);
// 获取NotificationManager实例
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// 检查Android版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Android 8.0及以上版本,创建一个通道
String channelId = "channel_id";
CharSequence channelName = "channel_name";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
notificationManager.createNotificationChannel(channel);
// 设置通道ID
builder.setChannelId(channelId);
}
// 发送通知
notificationManager.notify(notificationId, builder.build());
这段代码首先创建了一个通知构建器,然后创建一个用于点击通知时打开Activity的Intent,并将其设置为通知的点击动作。接下来,通过获取NotificationManager实例,检查Android版本,并根据版本创建通知通道(仅针对Android 8.0及以上版本)。
最后,调用notificationManager.notify()方法发送通知。每个通知都需要一个唯一的ID来标识,可以根据需求设置不同的notificationId。