Notification支持文字内容显示、震动、三色灯、铃声等多种提示形式,在默认情况下,Notification仅显示消息标题、消息内容、送达时间这3项内容。
1.更新系统通知Notification显示数据
1.1创建通知
/**
* 创建服务通知
*/
private fun createForegroundNotification(): Notification {
val builder: NotificationCompat.Builder = NotificationCompat.Builder(applicationContext, notificationChannelId)
//通知小图标
builder.setSmallIcon(R.mipmap.ic_launcher_round)
//通知标题
builder.setContentTitle("苏宁窖藏")
//通知内容
builder.setContentText("苏宁是国内优秀的跨国企业?$count")
//设置通知显示的时间
builder.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)
builder.setContentIntent(pendingIntent)
builder.priority = NotificationCompat.PRIORITY_DEFAULT
//设置为进行中的通知
builder.setOngoing(true)
//创建通知并返回
return builder.build()
}
1.2更新通知显示内容
- 其中notifyId是通知的唯一标识当通知的notify一致时,再发布通知则会覆盖原有的通知内容;这个方法也常用于实时更新通知内容;
- 前台服务发布通知的方法为startForeground(),使用方法和notificationManager.notify()类似,不需要另外再注册Manager;
主线程更新函数
private var count: Int = 0;
private val handler: Handler = Handler(Looper.getMainLooper());
private val mRunnable: Runnable = object : Runnable {
override fun run() {
val notification: Notification = createForegroundNotification()
//发送通知到状态栏
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//通知更新UI
// notificationManager.notify(NOTIFICATION_ID, notification);
//将服务置于启动状态 ,NOTIFICATION_ID指的是创建的通知的ID
startForeground(NOTIFICATION_ID, notification)
count++
handler.postDelayed(this, 1000)
}
}
2.如何删除关闭通知
1)通过NotificationCompat.Builder
设置setAutoCancel(true)
,这样当用户点击通知后,通知自动删除;
2)通过NotificationManager.cancel(id)
方法,删除指定 id 的通知;
3)通过 NotificationManager.cancelAll()
方法,删除该应用的所有通知;
3.通知栏自定义样式
自定义通知栏我们就要使用RemoteViews了,在SDK为16及以上才支持:
private fun getBigContentView(): RemoteViews{
return RemoteViews(this.packageName, R.layout.notify_big_content_view)
}
private fun getContentView(): RemoteViews{
return RemoteViews(this.packageName, R.layout.notify_content_view)
}
自定义通知栏会有大图样式和小图样式即普通样式和扩展样式,高度上边会有要求限制,普通样式高度不能超过64dp,扩展高度不能超过256dp;
今天我们主要讲一下大小图样式显示的适配;
如果我们可爱的产品和设计妹子给到了优美的大图样式,那我们的设置方法如下:
/**
* 创建服务通知
*/
private fun createForegroundNotification(): Notification {
val builder: NotificationCompat.Builder = NotificationCompat.Builder(applicationContext, notificationChannelId)
//通知小图标
builder.setSmallIcon(R.mipmap.ic_launcher_round)
//通知标题
builder.setContentTitle("苏宁窖藏&#