在 Android 9.0 上没有显示通知,但在8.0及以下版本上运行良好。我遇到了旧代码的问题,经过阅读发现需要在新的 Android 版本上传递 Channel,我从网上获取了这段代码,但仍无法在 Android 9.0 上工作。我不知道为什么。
我阅读了互联网上的所有内容,但通知仍未显示。
private void showSmallNotification( int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent){
String CHANNEL_ID = Constants.ChannelID;
String CHANNEL_NAME = "Notification";
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);;
NotificationCompat.Builder notification;
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
channel.enableVibration(true);
channel.setLightColor(Color.BLUE);
channel.enableLights(true);
channel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.notification),
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build());
channel.canShowBadge();
notificationManager.createNotificationChannel(channel);
notification = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
} else {
notification = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID);
}
notification
.setVibrate(new long[]{0, 100})
.setPriority(Notification.PRIORITY_MAX)
.setLights(Color.BLUE, 3000, 3000)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setWhen(getTimeMilliSec(timeStamp))
.setSmallIcon(R.mipmap.ic_launcher)
.setStyle(inboxStyle)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), icon))
.setContentText(message)
.build();
notificationManager.notify(CHANNEL_ID, 1, notification.build());
}