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

sch*_*ger 2 api notifications android backwards-compatibility

也许这个问题比我预期的要简单得多:我想显示notificationonCreatean的函数中创建的, 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);
Run Code Online (Sandbox Code Playgroud)

这表明NotificationCompat.Builder仅弃用上下文。我应该在较新版本中使用通知频道。

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

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

Com*_*are 7

我想显示在活动的 onCreate 函数中创建的通知。

请注意,这是显示Notification.

我错过了什么?

You need code to create the NotificationChannel that will only run on Android 8.0+ devices:

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));
}
Run Code Online (Sandbox Code Playgroud)

Then, for all API levels, pass in your channel identifier (here, CHANNEL_WHATEVER) to the NotificationCompat.Builder constructor. On older devices, the channel will be ignored.