Android通知Notification设置setSound无效解决办法

u=1678011113,2635959946&fm=26&gp=0.jpg

对于大于等于API 26 [Build.VERSION.SDK_INT >= Build.VERSION_CODES.O],您需要在通知通道上设置声音


fun createNotifyChannel(context: Context): String? {

    val sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.packageName + "/raw/" + R.raw.sound)
    // NotificationChannels are required for Notifications on O (API 26) and above.
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        val audioAttributes = AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
            .build()

        // Initializes NotificationChannel.
        val notificationChannel = NotificationChannel("huawei", "Sample Social", NotificationManager.IMPORTANCE_DEFAULT)
        notificationChannel.enableVibration(true) //是否有震动
        notificationChannel.lockscreenVisibility = notifPublicVisible()

        notificationChannel.setSound(sound, audioAttributes)
        // Adds NotificationChannel to system. Attempting to create an existing notification
        // channel with its original values performs no operation, so it's safe to perform the
        // below sequence.
        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(notificationChannel)
        "huawei"
    } else {
        // Returns null for pre-O (26) devices.
        null
    }
}

对于小于API 26 [Build.VERSION.SDK_INT < Build.VERSION_CODES.O],在NotificationCompat.Builder设置声音

val sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + packageName + "/raw/" + R.raw.sound)
NotificationCompat.Builder(context, channelId)
.setSound(sound)
.build()

最后尝试清除数据(或全新安装)
再试一次

参考自:https://www.thinbug.com/q/48986856

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。