每天学习一点点,成功增加一大步

解决 Fail to post notification on channel “null”

Android zhanghui 341℃

很久没有动过 android 之前学的时候用到过 notification ,但这次却遇到了这个问题,在模拟器中 MainActivity 中发送 notification 在通知栏中没有出现通知信息,但却出现了以下错误。

Fail to post notification on channel "null"

于是呼在网上寻找问题的原因点,找到的原因是在Android O后 引入了一个叫NotificationChannel的类 在sdk版本为26的时候 我们不加这个东西 就设置用不了点击事件。

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.baidu.com"));
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,0);

NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

 if(Build.VERSION.SDK_INT >= 26) 
 {
               //当sdk版本大于26
   String id = "channel_1";
   String description = "143";
   int importance = NotificationManager.IMPORTANCE_LOW;
   NotificationChannel channel = new NotificationChannel(id, description, importance);
//                     channel.enableLights(true);
//                     channel.enableVibration(true);//
   manager.createNotificationChannel(channel);
   Notification notification = new Notification.Builder(MainActivity.this, id)
                                    .setCategory(Notification.CATEGORY_MESSAGE)
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .setContentTitle("This is a content title")
                                    .setContentText("This is a content text")
                                    .setContentIntent(pendingIntent)
                                    .setAutoCancel(true)
                                    .build();
   manager.notify(1, notification);
   }
   else
   {
            //当sdk版本小于26
    Notification notification = new NotificationCompat.Builder(MainActivity.this)
                                    .setContentTitle("This is content title")
                                    .setContentText("This is content text")
                                    .setContentIntent(pendingIntent)
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .build();
    manager.notify(1,notification);
   }

参考文献:

https://blog.csdn.net/weixin_40604111/article/details/78674563

转载请注明:隨習筆記 » 解决 Fail to post notification on channel “null”

喜欢 (0)