Android8 通知适配

2019-01-09  本文已影响0人  鹅鹅鹅_

Android8中引入了通知渠道,大意就是将通知分组管理。
适配起来其实就是创建通知渠道,然后创建通知的时候将通知与通知渠道关联起来。
步骤

  1. 根据应用通知的种类分组,创建不同的channel注册到系统中
  2. 创建具体的通知时将通知与其所属的通知渠道通过channel id关联起来

所以我写了一个通知类工具,用来注册通知channel。在这里不创建Group也可以。

package com.xiaoxiaoqiquan.client.util;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationChannelGroup;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;


import com.xiaoxiaoqiquan.client.IApplication;
import java.util.concurrent.atomic.AtomicInteger;


public class NotificationUtil {
    public static String XQW_CHANNEL_ID = "xqw_channel_id";
    public static String XQW_CHANNEL_NAME = "xqw_channel_name";
    public static String XQW_CHANNEL_GROUP_ID = "XQW_GROPU_ID";
    public static String XQW_CHANNEL_GROUP_NAME = "小期旺通知组";
    private static AtomicInteger notityID = new AtomicInteger(1);

    @TargetApi(26)
    public static void channelInit() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager manager = (NotificationManager) IApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannelGroup(new NotificationChannelGroup(XQW_CHANNEL_GROUP_ID, XQW_CHANNEL_GROUP_NAME));

            NotificationChannel channel = new NotificationChannel(XQW_CHANNEL_ID, XQW_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            channel.setGroup(XQW_CHANNEL_GROUP_ID);
            channel.setShowBadge(true);
            channel.setBypassDnd(true);    //设置绕过免打扰模式
            channel.canBypassDnd();       //检测是否绕过免打扰模式
            channel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);//设置在锁屏界面上显示这条通知
            channel.setDescription("小期旺信息通知");
            channel.setLightColor(Color.GREEN);
            channel.setName("小期旺通知");
            channel.setShowBadge(true);
            channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            channel.enableVibration(true);

            manager.createNotificationChannel(channel);
        }
    }

    public static int nextNotifyId() {
        return notityID.getAndIncrement();
    }
}

在MainActiviy或者Application中调用注册通知渠道

NotificationUtil.channelInit();

之后发送通知就可以使用channel id绑定渠道了

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NotificationUtil.XQW_CHANNEL_ID);
效果图
上一篇 下一篇

猜你喜欢

热点阅读