一、通知渠道
Android8.0系统引入通知渠道的概念,每条通知都属于一个对应应用的渠道,通知渠道的控制权掌握在用户手上,创建通知渠道的步骤:
首先需要一个NotificationManager对通知进行管理,可以通过调用Context的getSystemService()方法获取,getSystemService()方法接收一个字符串参数用于确定获取系统的那个服务,这里传入Context.NOTIFICATION_SERVICE即可,接下来使用NotificationChannel类构建一个通知渠道,并调用NotificationManager的creatNotificationChannel()方法完成创建,创建一个通知渠道至少需要渠道ID、渠道名称以及重要等级3个参数,其中渠道ID可以随便定义,只要保证全局唯一即可,渠道名称是给用户看的,可以清楚的表达渠道的用途,渠道的等级依次从高到底,不同的重要等级会决定通知不同行为。通知一般创建在BroadcastReceiver和Service中。
Adnroid8.0之前是没有通知渠道的,对于这个问题的兼容使用AndroidX库中的NotificationCompat类,具体代码如下:
val manager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
val channel=NotificationChannel("nomal","Nomal",NotificationManager.IMPORTANCE_DEFAULT)
manager.createNotificationChannel(channel)
}
btnsend.setOnClickListener {
val notification=NotificationCompat.Builder(this,"nomal")
.setContentTitle("this is title")
.setContentText("content")
.setSmallIcon(R.mipmap.ic_launcher)
.build()
manager.notify(1,notification)
}
二、PendingIntent的使用
PendingIntent可以根据需要选择getActivity()方法、getBroadcast()方法、getService()方法。这几个方法接收的参数是相同的,第一个参数是Context,第二个参数一般用不到,传入0,第三个参数传入一个intent对象,第四个参数用于确定PendingIntent的行为,通常传入0就可以了,通过setContentIntent()方法,接收PendingIntent对象
val manager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
val channel= NotificationChannel("nomal","Nomal", NotificationManager.IMPORTANCE_DEFAULT)
manager.createNotificationChannel(channel)
}
sendAotice.setOnClickListener {
val intent=Intent(this,NoticeActivity::class.java)
val pi=PendingIntent.getActivity(this,0,intent,0)
val notification=NotificationCompat.Builder(this,"nomal")
.setContentTitle("this is title")
.setContentText("this is content")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pi)
.build()
manager.notify(1,notification)
}
点击消息通知取消的方法有两种
第一种:在NotificationCompat.Builder中再连缀一个setAutoCancel()方法,一种是显式的调用NotificationManager的cancel()方法将他取消
网友评论