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);