奥利奥模拟器上不显示通知

Notifications not showing on Oreo emulator

我一直在尝试在 Oreo 模拟器上显示一个简单的通知。奇怪的是,我什么也没看到。

让我们排除明显的答案:我尝试检查应用程序的通知,我尝试了 Notifications 和 NotificationCompat 路径。我试过有或没有频道,我试过有或没有组。

代码是初级的(是的,我使用 Kotlin 但它很容易理解):

class MainActivity : Activity() {

var id = 0

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val button:View = findViewById(R.id.button)
    button.setOnClickListener(this::onAddNotification)
}

private fun onAddNotification(v: View) {
    id++
    val builder = Notification.Builder(this).setSmallIcon(R.drawable.ic_notifications_none)
            .setContentTitle("Content #$id").setContentText("Content text for $id")

    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    notificationManager.notify(id, builder.build())
}
}

不用说,它的代码在 pre-Oreo 上运行完美。另一方面,Gmail 和地图会在该模拟器上显示通知。 我可能忘记了什么?

谢谢

正如 Tim Castelijns 在上面评论的那样...如果您正在使用 API26,您必须使用频道

切记 NotificationCompat 无法正确处理它(至于 2017 年 9 月 4 日),因此您的选择是:

  • 使用API 25 级或更早
  • 使用频道。请注意 Google 在 API 26 上弃用了 Builder(context) 构造函数。这是一个很好的理由。

我花了一个小时才意识到模拟器在 "Do Not Disturb" 上并且没有显示通知。

Google 说: 当您面向 Android 8.0(API 级别 26)时,您必须实施一个或多个通知渠道以向您的用户显示通知。如果您不以 Android 8.0(API 级别 26)为目标,但您的应用在设备 运行 Android 8.0(API 级别 26)上使用,您的应用程序的行为与在 运行 Android 7.1(API 级别 25)或更低设备上的行为相同。

https://developer.android.com/guide/topics/ui/notifiers/notifications.html