使用{{1}}和{{1}}时,有没有办法在Android Oreo上设置频道?
答案 0 :(得分:15)
由于NotificationManagerCompat
只是一个让生活更轻松的包装类,因此您可以正常创建通道:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = getString(R.string.channel_title)
val description = getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_HIGH
val mChannel = NotificationChannel(CHANNEL_ID, name, importance)
mChannel.description = description
mChannel.enableLights(true)
mChannel.lightColor = Color.parseColor("#5B3C88")
mChannel.enableVibration(true)
mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
val manager = (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
manager.createNotificationChannel(mChannel)
}
然后在发布通知时使用NotificationManagerCompat
,但不要忘记使用新构造函数构建通知:
NotificationCompat.Builder(context, CHANNEL_ID)
答案 1 :(得分:6)
我通常使用此类来管理通知渠道:
class NotificationManager(private val context: Context) {
companion object {
private val CHANNEL_ID = "YOUR_CHANNEL_ID"
private val CHANNEL_NAME = "Your human readable notification channel name"
private val CHANNEL_DESCRIPTION = "description"
}
@RequiresApi(Build.VERSION_CODES.O)
fun getMainNotificationId(): String {
return CHANNEL_ID
}
@RequiresApi(Build.VERSION_CODES.O)
fun createMainNotificationChannel() {
val id = CHANNEL_ID
val name = CHANNEL_NAME
val description = CHANNEL_DESCRIPTION
val importance = android.app.NotificationManager.IMPORTANCE_LOW
val mChannel = NotificationChannel(id, name, importance)
mChannel.description = description
mChannel.enableLights(true)
mChannel.lightColor = Color.RED
mChannel.enableVibration(true)
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
mNotificationManager.createNotificationChannel(mChannel)
}
}
然后你可以像这样使用util
fun createNotificationCompatBuilder(context: Context): NotificationCompat.Builder {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return NotificationCompat.Builder(context, NotificationManager(context).mainNotificationId)
} else {
return NotificationCompat.Builder(context)
}
}
通过这种方式,您可以在应用程序的任何位置使用它,就像您之前使用的一样,您可以在将来更改时轻松更改它。
答案 2 :(得分:0)
使用NotificationManagerCompat时是否可以在Android Oreo上设置频道?
NotificationManagerCompat
now支持通知渠道。新版本向NotificationManagerCompat
添加了通知通道方法,因此开发人员在处理通知时只能使用NotificationManagerCompat
。
在build.gradle文件中包括以下内容
implementation 'androidx.core.app:1.1.0-alpha03'