在按照书中的例子使用通知在设备上没有通知,查找资料后发现Android8后通知须要NotificationChannel,兼容 Android 8.0的通知以下:ide
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Intent intent = new Intent(this,NotificationMain2Activity.class); PendingIntent pi = PendingIntent.getActivity(this,0,intent,0); // 构建 Notification Notification.Builder builder = new Notification.Builder(this); builder.setContentTitle("ContentTitle") .setSmallIcon(R.drawable.ic_launcher_background) .setContentText("Content Text Here") .setContentIntent(pi) .setAutoCancel(true); // 兼容 Android 8.0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ String channelId = "ET_Notification_001"; String channelName = "ETtNotificationName"; // 第三个参数表示通知的重要程度 NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT); // 册后除非卸载再安装不然不改变 notificationManager.createNotificationChannel(notificationChannel); builder.setChannelId(channelId); } // 发出通知 notificationManager.notify(1, builder.build());