android发送通知的封装
android 8.0系统引入了渠道这个概念。每个应用可以有多个渠道,每个通知应该对应一个渠道。用户可以自由地选择这些通知渠道的重要程度,是否响铃、是否要关闭这个渠道的通知。
工具类:object NotificationUtil { /** * 创建渠道 */ fun createNotificationChannel(context: Context, config: ChannelConfig.() -> Unit) { val channelConfig = ChannelConfig(config) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = channelConfig.name val descriptionText = channelConfig.description val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(channelConfig.channelId, name, importance).apply { description = descriptionText } val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } /** * 发送通知 */ fun sendNotification(context: Context, config: NotificationConfig.() -> Unit) { val notificationConfig = NotificationConfig(config) val builder = NotificationCompat.Builder(context, notificationConfig.channelId) .setSmallIcon(notificationConfig.iconId) .setContentTitle(notificationConfig.title) .setContentText(notificationConfig.content) .setPriority(NotificationCompat.PRIORITY_DEFAULT) if (notificationConfig.isBig) { builder.setStyle( NotificationCompat.BigTextStyle() .bigText(notificationConfig.bigText) ) } with(NotificationManagerCompat.from(context)) { notify(notificationConfig.notificationId, builder.build()) } } /** * 用于配置渠道 */ class ChannelConfig(config: ChannelConfig.() -> Unit) { var channelId = "" var name: String = "" var description: String = "" init { config() } } /** * 用于配置通知 */ class NotificationConfig(config: NotificationConfig.() -> Unit) { var channelId = "" var notificationId = 0 @DrawableRes var iconId: Int = -1 var title: String = "" var content: String = "" var isBig: Boolean = false var bigText: String = "" init { config() } } }
调用例子:
创建渠道NotificationUtil.createNotificationChannel(BaseApp.i) { channelId = "channelId-01" name = "channelName" description = "channel 描述" }
发送通知NotificationUtil.sendNotification(BaseApp.i) { channelId = "channelId-01" notificationId = 110 iconId = R.mipmap.ic_launcher title = "这是标题" content = "这是内容" }
封装是为了更简单的使用。