1.如何创建通知?
/**
* 创建服务通知
*/
private fun createForegroundNotification(): Notification {
val notificationBuidler = NotificationCompat.Builder(applicationContext, notificationChannelId)
//通知小图标
notificationBuidler.setSmallIcon(R.mipmap.ic_launcher_round)
//通知标题
notificationBuidler.setContentTitle("苏宁窖藏")
//通知内容
notificationBuidler.setContentText("苏宁是国内优秀的跨国企业?$count")
//设置通知显示的时间
notificationBuidler.setWhen(System.currentTimeMillis())
//设定启动的内容
val activityIntent: Intent = Intent(this, MainActivity::class.java)
activityIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
val pendingIntent: PendingIntent = PendingIntent.getActivity(this,
1,activityIntent, PendingIntent.FLAG_UPDATE_CURRENT)
notificationBuidler.setContentIntent(pendingIntent)
//普通视图
notificationBuidler.setCustomContentView(getContentView())
//扩展视图
notificationBuidler.setCustomBigContentView(getBigContentView())
notificationBuidler.priority = NotificationCompat.PRIORITY_DEFAULT
//设置为进行中的通知
notificationBuidler.setOngoing(true)
//创建通知并返回
return notificationBuidler.build()
}
//发送通知给状态栏显示
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(NOTIFICATION_ID, notification)
1)借助Notification的帮助类NotificationCompat.Builder创建Notification;
2)设置Notification一些字段的值,例如:smallIcon,contentTitle,contentText,when等;
3)设置Notification点击以后的动作意图,由PendingIntent包裹,PendingIntent是主要包含Intent和一个要执行的目标动作,通过notificationBuidler.setContentIntent(pendingIntent)设置通知点击的目的Intent;
PendingInent对象获取方式不同,触发执行的意图也不同,触发后的意图总体来说有三种:进入某一Activity,发送广播,启动服务,分别调用PendingIntent.getActivity(...),PendingIntent.getBroadcast(...),PendingIntent.getService(...),PendingIntent.getActivities();在点击了通知栏的通知后,会触摸相应的意图,可以进入一个Activity,或发送一个广播,或启动一个服务。如果想实现一个自定义样式的通知,怎么做了?
4)创建RemoteViews,通过notificationBuidler.setCustomContentView(getContentView())设置要显示的自定义视图同时设置自定义视图点击意图;
RemoteViews构造方法中传入两个参数:包名,xml布局文件。这个xml布局文件对应如上通知中的界面,上面布局文件比较简单;
5)通过NotificationManager控制Notification显示notify()和移除canel();
private fun getContentView(): RemoteViews{
normalView = RemoteViews(this.packageName, R.layout.notify_content_view)
//上一首图标添加点击监听
val intent: Intent = Intent(PLAY_MUSIC)
intent.component = ComponentName("com.yifan.service", "com.yifan.service.PlayBroadcastReceiver")
val pendPreviousButtonIntent = PendingIntent.getBroadcast(