Android 佩戴 OS 时未触发通知

Notification not triggered on Android Wear OS

我正在玩弄 Wear OS 上的通知并使用 Android API 28.

在 Fossil Falster 3 上进行测试

为什么在独立应用程序中没有触发以下通知。 该代码几乎来自 Google documentation.

    button_in.setOnClickListener {
        val notificationId = 1
        // The channel ID of the notification.
        val id = "my_channel_01"
        // Build intent for notification content
        val viewPendingIntent = Intent(this, MainActivity::class.java).let { viewIntent ->
            PendingIntent.getActivity(this, 0, viewIntent, 0)
        }
        // Notification channel ID is ignored for Android 7.1.1
        // (API level 25) and lower.
        val notificationBuilder = NotificationCompat.Builder(this, id)
            .setLocalOnly(true)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("TITLE")
            .setContentText("TEXT")
            .setContentIntent(viewPendingIntent)

        NotificationManagerCompat.from(this).apply {
            notify(notificationId, notificationBuilder.build())
        }
        Log.d(TAG, "button was pressed!")
    }

我可以看到 "button was pressed!" 文本,但我没有收到任何通知。

Watch 应用程序需要一个通知渠道,不像 Android 应用程序那样不能这样工作。

在您的代码中,val notificationId = 1 指的是通知渠道 ID。

你可以构建一个NotificationChannel并像这样注册它:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    // Create the NotificationChannel
    val name = getString(R.string.channel_name)
    val descriptionText = getString(R.string.channel_description)
    val importance = NotificationManager.IMPORTANCE_DEFAULT
    val mChannel = NotificationChannel(1, name, importance) // 1 is the channel ID
    mChannel.description = descriptionText
    // Register the channel with the system; you can't change the importance
    // or other notification behaviors after this
    val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
    notificationManager.createNotificationChannel(mChannel)
}

注意注释代码,在val mChannel = ...中,您可以看到第一个参数值1指的是频道ID,正如您在OP中的代码中指定的那样。

您可以在此处阅读有关通知渠道的更多信息:https://developer.android.com/training/notify-user/channels