Android 8.0通知

先上8.0之前通知的代码

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("新消息"); builder.setContentText("你有一条新的消息"); builder.setDefaults(Notification.DEFAULT_SOUND); // 设置声音/震动等 //设置点击通知跳转页面后,通知消失 builder.setAutoCancel(true);
NotificationManager notificationManager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(11,builder.build())

在8.0之前这样写是没有问题的,但是在8.0的手机上,会发现无效,原因是没有设置setChannelId,至于为什么要这样做,后面再说,

NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setContentTitle("新消息"); builder.setContentText("你有一条新的消息");
builder.setChannelId("1");
builder.setDefaults(Notification.DEFAULT_SOUND); // 设置声音/震动等 //设置点击通知跳转页面后,通知消失 builder.setAutoCancel(true);
NotificationManager notificationManager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(11,builder.build());

直接setChannelId设置一个id就能解决8.0系统通知不显示的问题,如果要设置通知的点击效果

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
 builder.setSmallIcon(R.mipmap.ic_launcher);
 builder.setContentTitle("新消息");
 builder.setContentText("你有一条新的消息");
 builder.setDefaults(Notification.DEFAULT_SOUND); // 设置声音/震动等 //设置点击通知跳转页面后,通知消失 builder.setAutoCancel(true); builder.setChannelId("1");
 Intent intent = new Intent(this,MainActivity2.class);
 PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pi);  
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(11,builder.build());

这样就ok了

你可能感兴趣的:(Android 8.0通知)