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

标签 android api notifications backwards-compatibility

也许这个问题比我预期的要简单得多:我想显示一个 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/

相关文章:

android - 如何在android中将字符串从一个 Intent 获取到另一个 Intent

c# - ApiController 类如何工作和表现?

html - 有没有办法在 Chrome 关闭的情况下显示桌面通知?

java - 如何在 Swing 中创建通知

php - 如何使用 URL 中的 $_GET 参数重定向到同一页面

android - 模拟器中通知中的声音问题

android - 对于用作表达式的 Kotlin 函数,有没有简洁的操作和返回值的方式?

android - 如何检测按钮上的连续多次点击 - 就像android开发者选项

java - 编译器说变量尚未初始化

facebook - 我可以获取不在我域中的页面的 Facebook 点赞数吗?