在API 25或更低版本上触发通知时,没有抬头/声音

时间:2018-07-16 13:40:23

标签: android android-notifications android-support-library

在Android上使用NotificationCompat时,通知仅在API级别26或更高级别上可以正常工作。

  • 我想要:在每个可能的API级别(21+)上带有提示消息和声音的通知。
  • 我做到了:如notification docs
  • 中所述,设置一个NotificationChannel,设置频道重要性和通知优先级
  • 我得到:API级别26+上带有Heads-Up +声音的通知,API级别25或以下具有没有提示和没有声音的通知< / li>

代码:

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
  • 评分工具:3.1.3

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

1 个答案:

答案 0 :(得分:1)

可以使用以下声音播放声音:

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

或setSound的替代之一。例如:

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