在Android上使用NotificationCompat时,通知只能在API级别26或更高级别上按预期方式工作。


我想要:在每个可能的API级别(21+)上都带有提示消息和声音的通知。
我做到了:设置NotificationChannel,设置频道重要性和通知优先级,如notification docs中所述
我得到:API级别26+上带有抬头+声音的通知,API级别25或更低上没有抬头和声音的通知


码:

val chan2 = NotificationChannel(SECONDARY_CHANNEL,
    getString(R.string.noti_channel_second), NotificationManager.IMPORTANCE_HIGH)
manager.createNotificationChannel(chan2)

fun getNotification2(title: String, body: String): NotificationCompat.Builder {
    return NotificationCompat.Builder(applicationContext, SECONDARY_CHANNEL)
            .setContentTitle(title)
            .setContentText(body)
            .setSmallIcon(smallIcon)
            .setAutoCancel(true)
}

fun notifySecondaryChannel(id: Int, notification: NotificationCompat.Builder) {
    notification.priority = NotificationCompat.PRIORITY_MAX
    manager.notify(id, notification.build())
}


依存关系:


支持lib版本:27.1.1
编译/目标SDK:27
gradle工具:3.1.3


完整代码on github(派生和更新的Google示例)。

最佳答案

可以通过以下方式播放声音:

builder.setDefaults(Notification.DEFAULT_SOUND) or
builder.setDefaults(Notification.DEFAULT_ALL)


或setSound的替代之一。例如:

public Notification.Builder setSound (Uri sound,
                int streamType)

07-24 09:49
查看更多