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

How to create a Android notification with support to older API levels (e.g. lvl 23)

也许这个问题比我预期的要简单得多:我想显示一个 notification,它是在 ActivityonCreate 函数中创建的(出于调试原因) .

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

问题: 要创建和注册 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_WHATEVER)传递给 NotificationCompat.Builder 构造函数。在旧设备上,频道将被忽略。