Android Wear OS 上通知未触发

3

我正在玩弄Wear OS上的通知,并在配备Android API 28的Fossil Falster 3上进行测试。

为什么在独立应用程序中以下通知没有被触发?代码基本上是从Google文档中直接复制的。

    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!")
    }

我可以看到“按钮已按下”的文本,但我没有收到任何通知。

如果您正在直接在运行API 28的手表上运行的独立应用程序中,则需要创建通知通道。您在哪里进行此操作? - ianhanniballake
您的设备上的Android Wear应用程序是否可以访问通知?即在4.4中,您可以在“设置->安全性->通知访问”中找到此选项-在通知访问屏幕中,请确保已选中Android Wear。 - rshah
1个回答

1

观察应用需要通知通道,而 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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接