Android O通知适配
发布日期:2021-06-29 03:47:20 浏览次数:3 分类:技术文章

本文共 2510 字,大约阅读时间需要 8 分钟。

前言

从Android O(Android 8.0)开始,Google引入了通知渠道的概念。

什么是通知渠道呢?顾名思义,就是每条通知都要属于一个对应的渠道。每个App都可以自由地创建当前App拥有哪些通知渠道,但是这些通知渠道的控制权都是掌握在用户手上的。用户可以自由地选择这些通知渠道的重要程度,是否响铃、是否振动、或者是否要关闭这个渠道的通知。

对于每个APP而言,通知渠道的划分是非常需要仔细考究的。因为通知渠道一旦创建之后就不能再修改了,因此开发者需要仔细分析自己的APP一共有哪些类型的通知,然后再去创建相应的通知渠道。

是否一定要适配

如果我们将targetSdkVersion指定到了26或者更高,那么我们需要进行适配。

如何适配

这里非常关键的一个概念就是通知渠道了。
在【前言】中我们已经介绍了通知渠道,那么我们如何创建一个通知渠道呢?
创建一个通知渠道至少需要渠道ID、渠道名称以及重要等级这三个参数。渠道ID可以随便定义,只要保证全局唯一即可。渠道名称是给用户看的,需要能够表达清楚这个渠道的用途。重要等级的不同会决定通知的不同行为,当然这里只是初始状态下的重要等级,用户可以随时手动更改某个渠道的重要等级,App是无法干预的。

这里注意两点:

1、通知渠道功能是在Android O以上才有的,所以我们需要先检查系统版本。
2、创建通知渠道的代码只在第一次执行的时候才会创建,以后每次执行创建代码系统会检测到该通知渠道已经存在了,因此不会重复创建,也并不会影响任何效率。

下面我们直接上代码来演示如何适配

private void sendOrderNotificationWithAction(String orderId) {        Intent mainIntent = new Intent();        mainIntent.setClass(this, OrderManagementActivity.class);        mainIntent.putExtra("orderId", orderId);        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);        Notification notification;        if (Build.VERSION.SDK_INT >= 26) {            String channelId = "order";            String channelName = "订单消息";            int importance = NotificationManager.IMPORTANCE_HIGH;            createNotificationChannel(channelId, channelName, importance, notificationManager);            notification = new Notification.Builder(this, channelId)                    .setSmallIcon(R.mipmap.ic_launcher)                    .setContentText("收到一条待支付订单,查看详情")                    .setAutoCancel(true)                    .setContentIntent(pendingIntent)                    .build();        } else {            notification = new Notification.Builder(this)                    .setSmallIcon(R.mipmap.ic_launcher)                    .setContentText("收到一条待支付订单,查看详情")                    .setDefaults(Notification.DEFAULT_ALL)                    .setAutoCancel(true)                    .setContentIntent(pendingIntent)                    .build();        }        notificationManager.notify(0, notification);    }    @TargetApi(26)    private void createNotificationChannel(String channelId, String channelName, int importance, NotificationManager notificationManager) {        NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);        notificationManager.createNotificationChannel(notificationChannel);    }

转载地址:https://blog.csdn.net/zdj_Develop/article/details/88560313 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Android N行为变更 解决Android N上报android.os.FileUriExposedException
下一篇:Android之Notification详解

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月18日 23时07分47秒