/** * 创建通知 */ private void setUpNotification() { if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){ //安卓9.0发送通知 Notification.Builder builder = null; RemoteViews view_custom = new RemoteViews(getPackageName(), R.layout.update_download_notification_layout); view_custom.setTextViewText(R.id.name, notify_name + getString(R.string.app_name)); builder = new Notification.Builder(this, "chatChannelId"); //setSmallIcon 必须添加否则不能在通知栏显示(Android 8.0) builder.setSmallIcon(R.mipmap.ic_logo) .setBadgeIconType(3) .setNumber(1) .setAutoCancel(true); Intent resultIntent = new Intent(this, LoginActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(IndexMainActivity.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(resultPendingIntent); //setChannelId 必须添加否则不能在通知栏显示(Android 8.0) builder.setChannelId(getPackageName()); //createNotificationChannel 和 NotificationChannel必须添加,否则 Android9.0 不显示 NotificationChannel channel = new NotificationChannel( getApplication().getPackageName(), "通知栏消息", NotificationManager.IMPORTANCE_DEFAULT ); mNotificationManager.createNotificationChannel(channel); notification = builder.setContent(view_custom).build(); // mNotificationManager.notify((int) System.currentTimeMillis(), notification); mNotificationManager.notify(NOTIFY_ID, notification); }else { //先设定RemoteViews RemoteViews view_custom = new RemoteViews(getPackageName(), R.layout.update_download_notification_layout); view_custom.setTextViewText(R.id.name, notify_name + getString(R.string.app_name)); Notification.Builder builder1 = new Notification.Builder(getApplicationContext()); builder1.setSmallIcon(R.mipmap.ic_logo); //设置图标 builder1.setWhen(System.currentTimeMillis()); //发送时间 notification = builder1.setContent(view_custom).build(); mNotificationManager.notify(NOTIFY_ID, notification); // 通过通知管理器发送通知 } }
可参考https://blog.csdn.net/qq_31392539/article/details/93799917