Android O通知适配

前言
从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);
    }

猜你喜欢

转载自blog.csdn.net/zdj_Develop/article/details/88560313