很久以前写了一个通知的工具类,前两天拿来用,适配8.0的时候出了问题
爆了一个错误:
NotificationService: No Channel found for pkg=xxx.xxx.xxx, channelId=12345, id=12345, tag=null, opPkg=xxx.xxx.xxx, callingUid=10085, userId=0, incomingUserId=0, notificationUid=10085, notification=Notification…
突然想起来谷歌在8.0的时候对通知做了一些限制,于是去搜了一下资料
原来是要添加一个通道,绑定id
NotificationChannel channel = new NotificationChannel(id, name,NotificationManager.IMPORTANCE_HIGH); notificationManager.createNotificationChannel(channel);
之前的创建方式已经被表示为过时
builder = new Notification.Builder(context);
新的创建方法要把id加里面
builder = new Notification.Builder(context, id);
于是公共方法就成了
/** * 普通的Notification */ public void postNotification() { Notification.Builder builder; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(id, name,NotificationManager.IMPORTANCE_HIGH); notificationManager.createNotificationChannel(channel); builder = new Notification.Builder(context, id); }else { builder = new Notification.Builder(context); } //需要跳转指定的页面 Intent intent = new Intent(context, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendingIntent); builder.setTicker("new message") .setSmallIcon(R.drawable.ic_launcher_background) .setContentTitle("标题") .setContentText("内容") .setContentIntent(pendingIntent); activity notificationManager.notify(1,builder.build()); }
在activity中调用
notiUtil = new NotificationUtils(this); notiUtil.postNotification();