通知栏的已成为APP的基础配套功能了,有新的消息推送到通知栏,点击通知栏,进入指定的Activity,今天我们来分享通知栏的简单使用
第一步:创建 Notification,通过Notification.Builder设置属性
var CM_ID=0
val nm=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val intent=PendingIntent.getActivity(this, 0, Intent(this,TestActivity::class.java), 0)
// 传入参数:通道ID,通道名字,通道优先级(类似曾经的 builder.setPriority())
val channel= NotificationChannel(CM_ID, "name", NotificationManager.IMPORTANCE_HIGH)
nm.createNotificationChannel(channel)
val notify=Notification.Builder(this,CM_ID)
.setAutoCancel(true)//打开通知,该通知自动消失
.setContentTitle("测试信息")//通知标题
.setContentText("测试信息内容")//通知内容
.setSmallIcon(R.mipmap.logo)//通知图标
.setTicker("收到一条消息")//通知提示
.setWhen(System.currentTimeMillis())//通知时间
.setContentIntent(intent)//点击通知跳转界面
.build()
nm.notify(CM_ID,notify)//发送
nm.cancel(CM_ID)//取消
第二步:设置通道Channel的行为
// 配置通知渠道的属性
channel.setDescription(description)
// 设置通知出现时声音,默认通知是有声音的
channel.setSound(null, null)
// 设置通知出现时的闪灯(如果 android 设备支持的话)
channel.enableLights(true)
channel.setLightColor(Color.RED)
// 设置通知出现时的震动(如果 android 设备支持的话)
channel.enableVibration(true)
channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
//最后在 nm 中创建该通知渠道
nm.createNotificationChannel(channel)