Android中的Notification分为三种:
1、普通Notification
2、折叠Notification
3、悬浮Notification
1、普通Notification
//普通通知
val mIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://blog.csdn.net/qq_40716430/article/details/105690486"))
val pendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0)
val builder = NotificationCompat.Builder(this, "AppTestNotificationId")
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
.setAutoCancel(true)
.setContentTitle("普通通知")
.build()
// //添加如下代码,android版本需要手动添加NotificationChannel实现
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel("AppTestNotificationId", "AppTestNotificationName", NotificationManager.IMPORTANCE_DEFAULT)
nm!!.createNotificationChannel(notificationChannel)
}
nm!!.notify(1, builder)
效果如下:
2、折叠Notification
/**
*
*折叠式通知
*/
val mIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://blog.csdn.net/qq_40716430/article/details/105690486"))
val pendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0)
val remoteViews = RemoteViews(packageName, R.layout.view_fold)
val builder = NotificationCompat.Builder(this, "AppTestNotificationId")
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
.setAutoCancel(true)
.setContentTitle("折叠式通知")
val notification = builder.build()
//指定展开时的视图
notification.bigContentView=remoteViews
//添加如下代码,android版本需要手动添加NotificationChannel实现
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel("AppTestNotificationId", "AppTestNotificationName", NotificationManager.IMPORTANCE_DEFAULT)
nm!!.createNotificationChannel(notificationChannel)
}
nm!!.notify(1, notification)
效果如下:
3、悬浮Notification
/**
*
*悬挂式通知
* 如果不显示,看看App悬浮通知选项是否打开
*/
val mIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://blog.csdn.net/qq_40716430/article/details/105690486"))
val pendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0)
val builder = NotificationCompat.Builder(this, "AppTestNotificationId")
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
.setAutoCancel(true)
.setContentTitle("悬挂式通知")
//设置点击跳转
val hangIntent = Intent()
hangIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
hangIntent.setClass(this@MainActivity, MainActivity2::class.java)
val activity = PendingIntent.getActivity(this@MainActivity, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT)
builder.setFullScreenIntent(activity, true)
val notification = builder.build()
nm!!.notify(2, notification)
效果如下:
关注公众号,不迷路喔