我创建了一个函数来显示应用程序中任何位置的通知。它可以正常工作,但是即使我专门为其编写代码,这些通知也不会使我们颤抖。我尚未在较旧的手机上对其进行测试,但肯定无法在Android 9上运行。这是我的代码:
fun displayLocalNotif(
context: Context,
notifId: Int,
tapOpenActivityClass: Class<*>,
channelName: String,
notifTitle: String,
notifText: String
) {
val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelId = channelName.toLowerCase(Locale.ROOT).replace(" ", "_")
val intent = Intent(context, tapOpenActivityClass).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId,
channelName,
NotificationManager.IMPORTANCE_DEFAULT
)
channel.lightColor = Color.WHITE
channel.enableLights(true)
val audioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
channel.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, audioAttributes)
channel.enableVibration(true)
channel.setShowBadge(true)
notificationManager.createNotificationChannel(channel)
}
val builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(notifTitle)
.setContentText(notifText)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setVibrate(longArrayOf(1000, 1000))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
with(NotificationManagerCompat.from(context)) {
notify(notifId, builder.build())
}
}
我希望这些通知能够发出默认的通知声音,振动并默认显示在锁定屏幕上。我该怎么办?