进度通知
private val handler = Handler()
private var count = 0
private lateinit var refreshNotify:ProgressNotify
// 开始播放进度通知的刷新动画
private fun startProgressNotify(title: String,message: String) {
count = 0
refreshNotify = ProgressNotify(title,message)
handler.post(refreshNotify)
}
// 定义一个持续发送进度通知的任务内部类
private inner class ProgressNotify(val title: String,val message: String) : Runnable{
override fun run() {
sendProgressNotify(title,message,count)
count++
if (count<=100){
handler.postDelayed(refreshNotify,200)
}
}
}
// 发送单次进度通知
private fun sendProgressNotify(title: String, message: String, progress: Int) {
}
浮动通知
关键是调用 Notification.Builder 对象的 setFullScreenIntent,该方法定义了浮动窗的点击事件以及优先级。
private fun sendFloatNotify(title:String, message:String){
// 声明一个点击通知消息时触发的动作意图
val clickIntent = intentFor<ProgressBarActivity>()
val piClick = PendingIntent.getActivity(this,
R.string.app_name,clickIntent,PendingIntent.FLAG_UPDATE_CURRENT)
// 构建通知
val notification = Notification
.Builder(this,resources.getString(R.string.notify_id))
.setContentIntent(piClick)
.setAutoCancel(true)
.setSmallIcon(R.drawable.default_icon)
.setTicker("简单消息")
.setWhen(System.currentTimeMillis())
.setLargeIcon(BitmapFactory.decodeResource(resources,R.drawable.icon_default_header))
.setContentTitle(title)
.setContentText(message)
.setFullScreenIntent(piClick,true)
.build()
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
// 发送通知
manager.notify(R.string.app_name,notification)
}
锁屏通知
设置锁屏通知的关键是设置 Notification.Builder 对象的 setVisibility,该方法用于指定通知消息在锁屏状态下的显示方式。
// 显示通知的全部内容
Notification.VISIBILITY_PUBLIC
// 显示基本信息
Notification.VISIBILITY_PRIVATE,
// 不显示任何内容,包括图标
Notification.VISIBILITY_SECRET
,
private fun sendLockNotify(title:String, message:String,visible:Boolean){
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
Toast.makeText(this, "锁屏通知需要5.0以上系统支持", Toast.LENGTH_SHORT).show()
return
}
// 声明一个点击通知消息时触发的动作意图
val clickIntent = intentFor<ProgressBarActivity>()
val piClick = PendingIntent.getActivity(this,
R.string.app_name,clickIntent,PendingIntent.FLAG_UPDATE_CURRENT)
// 构建通知
val notification = Notification
.Builder(this,resources.getString(R.string.notify_id))
.setContentIntent(piClick)
.setAutoCancel(true)
.setSmallIcon(R.drawable.default_icon)
.setTicker("简单消息")
.setWhen(System.currentTimeMillis())
.setLargeIcon(BitmapFactory.decodeResource(resources,R.drawable.icon_default_header))
.setContentTitle(title)
.setContentText(message)
// 设置锁屏通知的可见性
.setVisibility(if(visible) Notification.VISIBILITY_PUBLIC else Notification.VISIBILITY_PRIVATE)
.build()
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
// 发送通知
manager.notify(R.string.app_name,notification)
}