【问题标题】:How to create a Android notification with support to older API levels (e.g. lvl 23)如何创建支持旧 API 级别的 Android 通知(例如 lvl 23)
【发布时间】:2017-12-05 12:57:13
【问题描述】:

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

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

【问题讨论】:

    标签: android api notifications backwards-compatibility


    【解决方案1】:

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

    请注意,这是显示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 构造函数。在旧设备上,该频道将被忽略。

    【讨论】:

    • 注意:创建时间或多或少是出于调试原因。将其设置为可选参数是有意义的。谢谢;)
    • @schlenger:“创建时间或多或少是出于调试原因”——嗯,好的。
    • 一团糟……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    相关资源
    最近更新 更多