按书中代码运行无法显示通知;
原因是Android 8.0 引入了通知渠道,其允许您为要显示的每种通知类型创建用户可自定义的渠道。用户界面将通知渠道称之为通知类别。targeSdk升级到26之后,所有的通知的实现都需要提供通知渠道,如果不提供通知渠道的话,所有通知在8.0系统上面都不能正常展示。
因此NotificationCompat.Builder(this)被替换为NotificationCompat.Builder(this,channelId),并需要创建渠道。
代码如下:
NotificationChannel channel = new NotificationChannel("1", "Channel1", NotificationManager.IMPORTANCE_DEFAULT); channel.enableLights(true); //是否在桌面icon右上角展示小红点 channel.setLightColor(Color.GREEN); //小红点颜色 channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知 NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE); manager.createNotificationChannel(channel); int notificationId = 0x1234; Notification notification=new NotificationCompat.Builder(this,"1") .setDefaults(Notification.DEFAULT_ALL) .setContentTitle("This is contenttitle") .setContentText("This is content text") .setWhen(System.currentTimeMillis()) .setPriority(Notification.PRIORITY_MAX) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher)).build(); manager.notify(1,notification); break;
参考:https://blog.csdn.net/rentee/article/details/78303532;
https://blog.csdn.net/cch___/article/details/78552395