【问题标题】:Can't silence notification on Android API29无法在 Android API 29 上静音通知
【发布时间】:2021-06-28 07:20:07
【问题描述】:

需要使前台服务显示的通知静音。为了使通知静音,我使用了许多 SO 建议的解决方案。但是似乎没有什么可以使烦人的通知声音静音。它在 SDK25 上被静音。但在 SDK 29 模拟器上,它不会被静音。有什么解决办法?

代码:

//service

override fun onBind(intent: Intent?): IBinder? {
    return null
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

    createNotificationChannel()

    val notificationIntent = Intent(this, MainActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(
        this,
        0, notificationIntent, 0
    )
    val notification: Notification =
        NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("app_name")
            .setContentText("Updating database.")
            .setSmallIcon(R.drawable.logo)
            .setContentIntent(pendingIntent)
            .build()
    startForeground(1, notification)

    thread() {
        Thread.sleep(3000)
        stopSelf()
    }

    return START_NOT_STICKY
}


override fun onDestroy() {
    super.onDestroy()
}

private fun createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val name = SettingsHelper.KEY_NOTIFICATION_channel_name_service
        val description = SettingsHelper.KEY_NOTIFICATION_CH_ID_SERVICE
        val channel = NotificationChannel(
            SettingsHelper.KEY_NOTIFICATION_CH_ID,
            name,
            NotificationManager.IMPORTANCE_NONE
        )
        channel.description = description
        channel.setSound(null, null)

        val manager = getSystemService(
            NotificationManager::class.java
        )

        manager.createNotificationChannel(channel)
    }
}

【问题讨论】:

  • 您能否发布所有用于创建通知的代码?
  • @Skizo-ozᴉʞS 我已更新所有服务代码以重现。它会播放通知声音。
  • 你试过用空的声音文件代替null吗?
  • @Rifat 你试过我的解决方案了吗?
  • @Skizo-ozᴉʞS 当我使用 NotificationCompat.Builder 时,我不必使用 setSilent(),默认情况下它是无声的。为了安全起见,我还是使用了它。感谢您的建议和努力。

标签: android android-notifications


【解决方案1】:

您可以使用 NotificationCompat.Builder 中的setSilent()

如果为 true,则不管通知或通知通道上设置的声音或振动如何,都会使该通知实例静音。如果为 false,则应用正常的声音和振动逻辑。默认为 false。

请注意,如果您要更改通知设置,我建议您每次卸载并重新安装该应用程序,因为它可能不会更新您在新运行中设置的设置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    相关资源
    最近更新 更多