Notification在android 8.0以上設置時,需要設置渠道信息才能夠正常顯示通知。本以爲很簡單,上網查了很多資料都不行,後面決定自己去看Notifacation的源碼,終於找到了解決方案,在這裏和大家做個分享。廢話不多說,直接上代碼:
String id = "my_channel_01";
String name="我是渠道名字";
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
Toast.makeText(this, mChannel.toString(), Toast.LENGTH_SHORT).show();
Log.i(TAG, mChannel.toString());
notificationManager.createNotificationChannel(mChannel);
notification = new Notification.Builder(this)
.setChannelId(id)
.setContentTitle("5 new messages")
.setContentText("hahaha")
.setSmallIcon(R.mipmap.ic_launcher).build();
} else {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("5 new messages")
.setContentText("hahaha")
.setSmallIcon(R.mipmap.ic_launcher)
.setOngoing(true)
.setChannel(id);//無效
notification = notificationBuilder.build();
}
notificationManager.notify(111123, notification);
---------------------
作者:南風裏
來源:CSDN
原文:https://blog.csdn.net/qq_35749683/article/details/80451791
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!