在表示此帖子重复之前,请查看完整的说明。我到处都是,似乎找不到解决我问题的方法。
问题 在我的应用程序中,通知不会在Android 8或更高版本上显示。我似乎根本没有收到任何通知来显示 。
到目前为止,我尝试了什么?
我看过this个帖子,this个帖子,还有一些类似this的教程。
所有人都在谈论设置smallIcon,contentTitle,contentText和通知通道。我做了所有这些,但是没有任何明显的成功。
我的代码
在我的NotificationHelper类中,我具有以下方法:
public NotificationHelper(Context base) {
super(base);
createChannels();
}
public void createChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Android 8 or higher? Set notification channel
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,CHANNEL_ONE_NAME,Notificationmanager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
getManager().createNotificationChannel(notificationChannel);
}
}
private Notificationmanager getManager() {
if (notifyManager == null) {
notifyManager = (Notificationmanager) getSystemService(Context.NOTIFICATION_SERVICE);
}
return notifyManager;
}
public Notification getNotification1(Context context) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,CHANNEL_ONE_ID)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notification_alert); // alert icon.
return builder.build();
}
public void notify(int id,Notification notification) {
Log.i("NotificationHelper","Notifying with notification: " + notification.toString());
getManager().notify(id,notification);
}
然后在我的Mainactivity中,在onButtonClick事件中具有以下方法(显然是在Mainactivity的onCreate()方法中实例化notificationHelper对象之后):
Notification notification = notificationHelper.getNotification1(this);
notificationHelper.notify(NotificationHelper.notification_one,notification);
有人有什么想法吗?
编辑:事实证明,在模拟器上运行时,代码可以正常工作。如here所示,电池优化设置可能有问题。