您可以尝试以下源代码
public void showNotification()
{
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,"channelID")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Notification")
.setContentText("Hello! This is a notification.")
.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
createChannel(notificationManager);
notificationManager.notify(notificationId, notificationBuilder.build());
}
public void createChannel(NotificationManager notificationManager){
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationChannel channel = new NotificationChannel("channelID","name", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Hello! This is a notification.");
notificationManager.createNotificationChannel(channel);
}
此代码适用于每个 android 版本。这是git 仓库