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個渠道。
可以看到通知4在最前面。且通知3、4來的時候手機會有提示音,通知4相比3會彈出通知窗口