也许这个问题比我预期的要简单:我想显示一个notification
,在Activity
的onCreate
函数中创建(出于调试原因)。
Android Studio 3.0.1
,API LVL 23(支持旧设备)并在具有API LVL 27的Nexus5设备上运行。
显示通知的代码:
PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
Notification notification = new NotificationCompat.Builder(this)
.setTicker("SomethingTicker")
.setSmallIcon(R.drawable.someImage)
.setContentTitle("SomeTitle")
.setContentText("SomeText")
.setContentIntent(pi)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(001, notification);
表明只有上下文的 NotificationCompat.Builder
被弃用。我应该在较新版本中使用通知频道。
问题:要创建并注册一个通知通道,我必须使用API LVL> 27。
我想念什么?最好的方法是什么
我想显示一个在活动的发作函数中创建的通知。
请注意,这是显示Notification
的奇怪时间。
我缺少什么?
您需要代码来创建仅在Android 8.0 设备上运行的NotificationChannel
:
NotificationManager mgr=
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O &&
mgr.getNotificationChannel(CHANNEL_WHATEVER)==null) {
mgr.createNotificationChannel(new NotificationChannel(CHANNEL_WHATEVER,
"Whatever", NotificationManager.IMPORTANCE_DEFAULT));
}
,对于所有API级别,将您的通道标识符(此处,CHANNEL_WHATEVER
)传递到NotificationCompat.Builder
构造函数。在较旧的设备上,该通道将被忽略。