1、首先创建一个NotifyManager对通知进行管理,调用Context的 getSystemService() 方法。getSystemService() 方法用于接收一个字符串来确定从系统获取什么服务:Context.NOTIFICATION_SERVICE 代表获取系统的通知服务。
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
var channel =
NotificationChannel("normal", "Normal", NotificationManager.IMPORTANCE_DEFAULT)
manager.createNotificationChannel(channel)
}
2、使用 NotificationChannel 类创建实例,传入的参数为:
channelId:代表这个通知的渠道ID 具有唯一性
channelName:该通知渠道名称
通知的重要等级:重要等级主要有IMPORTANCE_HIGH、IMPORTANCE_DEFAULT、
IMPORTANCE_LOW、IMPORTANCE_MIN这几种
由于NotificationChannel类和createNotificationChannel()方法都是Android 8.0系统中新增的API,因此我们在使用的时候还需要进行版本判断才可以!!!!
3、使用 NotificationCompat.Builder 来构建通知对象。
NotificationCompat.Builder 中接收两个参数:第一个参数是context,这个没什么好说的;第二个参数是渠道ID。还提供了对通知设置内容的多种方法,其它的方法功能如名称所示!!
sendNotice.setOnClickListener {
val notification =
NotificationCompat.Builder(this, "normal").setContentTitle("This is content title")
.setContentText("This is content text!").setSmallIcon(R.drawable.small_icon)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.large_icon))
.setContentIntent(pendingIntent)
.build()
manager.notify(1, notification)
4、设置点击通知功能
使用 PendingIntent ,PendingIntent提供了很多方法:getActivity()方法、getBroadcast()方法,还是getService()方法,这几个方法的参数相同:
第一个:Context
第二个:参数一般用不到,传入0即可
第三个是一个Intent对象,用于构建PendingIntent的“意图”
第四个用于确定PendingIntent的行为,有FLAG_ONE_SHOT、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT和FLAG_UPDATE_CURRENT这4种值可选
sendNotice.setOnClickListener {
val intent = Intent(this, NotificationActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, FLAG_MUTABLE)
val notification =
NotificationCompat.Builder(this, "normal").setContentTitle("This is content title")
.setContentText("This is content text!").setSmallIcon(R.drawable.small_icon)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.large_icon))
.setContentIntent(pendingIntent).setAutoCancel(true)
.build()
manager.notify(1, notification)
}
setAutoCancel 为设置当点击通知后,通知自动取消的功能。
5、进阶技巧
NotificationCompat.Builder 中提供了非常丰富的API,以便我们创建出更加多样的通知效果!!
(1) setStyle() 用于通知显示 长文本、大图片等功能的实现。实现代码:
长文本:
.setStyle(
NotificationCompat.BigTextStyle().bigText(
"This is content text!This is content text!This is content text!" +
"This is content text!This is content text!This is content text!" +
"This is content text!This is content text!This is content text!")
)
.build()
大图片:
.setStyle(NotificationCompat.BigPictureStyle().bigPicture(
BitmapFactory.decodeResource(resources, R.drawable.big_image)))