gpt4 book ai didi

android - 如何创建支持旧 API 级别(例如 23 级)的 Android 通知

转载 作者:行者123 更新时间:2023-11-29 16:46:50 25 4
gpt4 key购买 nike

也许这个问题比我预期的要简单得多:我想显示一个 notification , 在 onCreate 内创建Activity 的功能(出于调试原因)。

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只有上下文被弃用。我应该在较新版本中使用通知 channel 。

问题:要创建和注册 NotificationChannel,我必须使用 api lvl >27。

我错过了什么?最好的方法是什么

最佳答案

I want to display a notification, created within the onCreate function of an Activity.

请注意,这是显示 Notification 的奇怪时间。

What am I missing?

您需要代码来创建只能在 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 标识符(此处为 CHANNEL_WHATEVER)传递给 NotificationCompat.Builder 构造函数。在旧设备上, channel 将被忽略。

关于android - 如何创建支持旧 API 级别(例如 23 级)的 Android 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47654189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com