android8.0 通知适配(NotificationChan

作者: 柳白之道 | 来源:发表于2018-01-09 15:27 被阅读4632次

    NotificationChannel是android8.0新增的特性,如果App的targetSDKVersion>=26,没有设置channel通知渠道的话,就会导致通知无法展示。

    Android O 引入了 通知渠道(Notification Channels),以提供统一的系统来帮助用户管理通知,如果是针对 android O 为目标平台时,必须实现一个或者多个通知渠道,以向用户显示通知。比如聊天软件,为每个聊天组设置一个通知渠道,指定特定声音、灯光等配置。

    国内app基本都集成了第三方推送SDK,目前使用的两个推送平台都还没进行适配,所以还需要等第三方出新版本并集成,如果我们app内部也有自己弹出通知逻辑,最好和他们保持一致,毕竟app内设置多个通知渠道不方便维护。

    报错内容:

    Failed to post notification on channel “null” Target Api is 26

    1、临时方案

    当然,google也考虑到适配问题,临时兼容方案是targetSDKVersion低于26

    2、最终方案

    创建channel

    部分代码如下:

    String channelID = "1";
    
    String channelName = "channel_name";
    
    NotificationChannel channel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
    
    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
    
    manager.createNotificationChannel(channel);
    
    Notification.Builder builder =new Notification.Builder(context);
    
    builder.setContentText(msgDesc);
    
    builder.setContentTitle(msgTitle);
    
    //创建通知时指定channelID
    
    builder.setChannelId(channelID);
    
    Notification notification = builder.build();
    

    此时,推送通知,不再有上面的错误提示,同时可以看到顶部有通知正常弹出。

    上面代码是针对android8.0,上线我们还要兼容低版本系统以及channel属性设置。

    具体可以参看StackOverFlow和Startrainee这篇文章:

    https://stackoverflow.com/questions/45711925/failed-to-post-notification-on-channel-null-target-api-is-26

    https://www.jianshu.com/p/92afa56aee05

    相关文章

      网友评论

        本文标题:android8.0 通知适配(NotificationChan

        本文链接:https://www.haomeiwen.com/subject/xhxgnxtx.html