在Android Wear OS上未触发通知

问题描述 投票:3回答:1

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

为什么在一个独立的应用程序中,以下通知没有被触发。谷歌文档.

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

我可以看到 "按钮被按下!"的文字,但我没有收到任何通知。

android kotlin android-notifications wear-os
1个回答
1
投票

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,正如您在上位机中的代码所指定的那样。

你可以在这里阅读更多关于通知渠道的内容。https:/developer.android.comtrainingnotify-userchannels。

© www.soinside.com 2019 - 2024. All rights reserved.