Android—关于通知NotificationManager操作

Android8.0引入NotificationChannel,每条通知都有对应的渠道,渠道创建后不可更改

1.要用到通知功能必不可少就是获取一个NotificationManager对象

val manager= getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        

2.创建自己所需要的渠道

if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
    al channel1 = NotificationChannel("channel1","通知测试1",NotificationManager.IMPORTANCE_MIN)
    val channel2 = NotificationChannel("channel2","通知测试2",NotificationManager.IMPORTANCE_LOW)
    val channel3 = NotificationChannel("channel3","通知测试3",NotificationManager.IMPORTANCE_DEFAULT)
    val channel4 = NotificationChannel("channel4","通知测试4",NotificationManager.IMPORTANCE_HIGH)
    manager.apply {
       createNotificationChannel(channel1)
       createNotificationChannel(channel2)
       createNotificationChannel(channel3)
       createNotificationChannel(channel4)
    }
}

创建4个渠道,对应通知4中重要程度

3.创建PendingIntent对象,点击通知打开你所要显示的界面

val intent = Intent(this,First::class.java)
val pi = PendingIntent.getActivity(this,0,intent,0)

4.创建通知

        btn1.setOnClickListener {
            val notification1 = NotificationCompat.Builder(this,"channel1")
                .setContentTitle("测试通知1")
                .setContentText("通知1来了,通知1来了,通知1来了")
                .setSmallIcon(R.drawable.touxiang)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.b))
                .build()
            manager.notify(1,notification1)
        }
        btn2.setOnClickListener {
            val notification2 = NotificationCompat.Builder(this,"channel2")
                .setContentTitle("测试通知2")
                .setContentText("通知2来了,通知2来了,通知2来了")
                .setSmallIcon(R.drawable.c)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.huangqiong))
                .build()
            manager.notify(2,notification2)
        }
        btn3.setOnClickListener {
            val notification3 = NotificationCompat.Builder(this,"channel3")
                .setContentTitle("测试通知3")
                .setContentText("通知3来了,通知3来了,通知3来了")
                .setSmallIcon(R.drawable.leimu)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.linlin))
                .build()
            manager.notify(3,notification3)
        }
        btn4.setOnClickListener {
            val notification4 = NotificationCompat.Builder(this,"channel4")
                .setContentTitle("测试通知4")
                .setContentText("通知4来了,通知4来了,通知4来了")
                .setSmallIcon(R.drawable.liuyuan)
                .setStyle(NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(),R.drawable.yating)))
                .setContentIntent(pi)
                .setAutoCancel(true)
                .build()
            manager.notify(4,notification4)
        }

我这里创建4个按钮事件分别对应4个通知,4个通知对应不同的4个渠道。

Android—关于通知NotificationManager操作_第1张图片

可以看到通知4在最前面。且通知3、4来的时候手机会有提示音,通知4相比3会弹出通知窗口

你可能感兴趣的:(Android)