GLNotifiactionManager.java 12.6 KB
package com.glsx.pushsdk.manager;

import android.annotation.SuppressLint;
import android.app.AppOpsManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.blankj.utilcode.util.LogUtils;
import com.glsx.pushsdk.R;
import com.glsx.pushsdk.receiver.GLMessageClickedReceiver;
import com.glsx.pushsdk.tools.Tools;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 通知栏消息管理
 *
 * @author YFZX-yulg
 */
@SuppressWarnings({"deprecation","unchecked"})
public class GLNotifiactionManager {
    private static String TAG = GLNotifiactionManager.class.getSimpleName();
    public static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
    public static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
    private NotificationCompat.Builder mBuilder;
    private NotificationManager mNotificationManager;
    private Notification mNotification;
    private int NOTIFICATION_FLAG = 1001;//通知ID,不重复,可以产生多个通知显示
    private final String CHANNEL_ID = "1000";

    private static GLNotifiactionManager mGLNotificationManager = new GLNotifiactionManager();

    public static GLNotifiactionManager getInstance() {
        if (mGLNotificationManager == null) {
            synchronized (GLNotifiactionManager.class) {
                if (mGLNotificationManager == null) {
                    mGLNotificationManager = new GLNotifiactionManager();
                }
            }
        }
        return mGLNotificationManager;
    }

    private GLNotifiactionManager() {
        init();
    }

    /**
     * 初始化我的通知栏
     */
    private void init() {
        mNotificationManager = (NotificationManager) GLPushManager.getInstance().getMyContext()
                .getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        mBuilder = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) ?
                new NotificationCompat.Builder(GLPushManager.getInstance().getMyContext(), CHANNEL_ID) :
                new NotificationCompat.Builder(GLPushManager.getInstance().getMyContext());

    }

    /**
     * 设置通知栏通知
     *
     * @param title
     */
    @SuppressWarnings("deprecation")
    @SuppressLint("InlinedApi")
    public void setUpNotification(String title, String content, String value, String msgId) {

        LogUtils.i(TAG, "接收到推送通知, title = " + title);
        if (mBuilder == null) {
            init();
        }

        //应用在前台时,直接应用展示消息弹框
        //应用在后台且未被清理时,以消息形式展示在消息通知栏内
        if (Tools.isTopActivity(GLPushManager.getInstance().getMyContext())) {
            LogUtils.i(TAG, "Tools.isTopActivity 11111 ");
            Intent intent1 = new Intent();
            intent1.putExtra(GLLoginManager.ACCEPT_RECEIVER_TITLE, title);
            intent1.putExtra(GLLoginManager.ACCEPT_RECEIVER_CONTENT, content);
            intent1.putExtra(GLLoginManager.ACCEPT_RECEIVER_VALUE, value);
            intent1.putExtra(GLLoginManager.ACCEPT_RECEIVER_MSG_ID, msgId);
            intent1.setAction(GLLoginManager.ACCEPT_RECEIVER_NOTIFICATION);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String pakName = GLPushManager.getInstance().getMyContext().getPackageName();
                intent1.setComponent(new ComponentName(pakName, pakName + ".glpush.GLAcceptReceiver"));
                GLPushManager.getInstance().getMyContext().sendBroadcast(intent1);
                LogUtils.i(TAG, "发送广播, intent1,pakName = " + pakName);

            } else {
                GLPushManager.getInstance().getMyContext().sendBroadcast(intent1);
            }

            return;
        }

        LogUtils.i(TAG, "准备进行推送, mBuilder = " + mBuilder);

        Drawable appIcon = Tools.getAppIcon(GLPushManager.getInstance().getMyContext());
        String appName = Tools.getAppName(GLPushManager.getInstance().getMyContext());
        String pushTitle = appName + "-" + title;

        LogUtils.i(TAG, "准备进行推送, appName = " + appName);
        LogUtils.i(TAG, "准备进行推送, pushTitle = " + pushTitle);

        //通知栏消息点击执行意图
        Intent clickIntent = new Intent(GLPushManager.getInstance().getMyContext(), GLMessageClickedReceiver.class); // 点击通知之后要发送的广播
        //Intent clickIntent = new Intent(GLPushManager.getInstance().getMyContext(), com.glsx.aicar.ui.activity.MainActivity.class); // 点击通知之后要发送的广播
        clickIntent.setAction(GLMessageClickedReceiver.RECEIVER);
        clickIntent.putExtra(GLLoginManager.ACCEPT_RECEIVER_TITLE, title);
        clickIntent.putExtra(GLLoginManager.ACCEPT_RECEIVER_CONTENT, content);
        clickIntent.putExtra(GLLoginManager.ACCEPT_RECEIVER_VALUE, value);
        clickIntent.putExtra(GLLoginManager.ACCEPT_RECEIVER_MSG_ID, msgId);

        int id = (int) (System.currentTimeMillis() / 1000);

        //创建PendingIntent,便于在应用非前台时通过客户点击通知栏消息时触发执行弹框和后续操作,不点击消息则不执行后续操作
        PendingIntent contentIntent = PendingIntent.getBroadcast(
                GLPushManager.getInstance().getMyContext(),
                id, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        //PendingIntent contentIntent = PendingIntent.getActivity(GLPushManager.getInstance().getMyContext(), 0,clickIntent, 0);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (!openNotificationChannel(GLPushManager.getInstance().getMyContext(),
                    mNotificationManager, CHANNEL_ID)) {
                return;
            }
        }
        mBuilder.setContentTitle(pushTitle)// 设置title
                .setContentText(content)// 设置内容
//				.setLargeIcon(Tools.Drawable2Bitmap(appIcon)) // 设置大标题
                .setSmallIcon(R.drawable.notify_logo)
//				.setSmallIcon(Tools.getId(GLPushManager.getInstance().getMyContext(), "drawable","app_logo")) // 设置小图标
                .setTicker(content) // 通知首次出现在通知栏,带上升动画效果的
                .setAutoCancel(true)// 设置这个标志当用户单击面板就可以让通知将自动取消
                .setWhen(System.currentTimeMillis())// 通知产生的时间,会在通知信息里显示,一般是系统获取到的时间
                .setPriority(Notification.PRIORITY_DEFAULT) // 设置该通知优先级
                .setDefaults(Notification.DEFAULT_ALL) // 设置震动,响声
                .setContentIntent(contentIntent);// 设置点击跳转

        LogUtils.i(TAG, "准备进行推送, pushTitle1 = " + pushTitle);
//		mNotification = mBuilder.getNotification();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "消息类型",
                    NotificationManager.IMPORTANCE_HIGH
            );
            mNotificationManager.createNotificationChannel(channel);
        }
        mNotification = mBuilder.build();

        mNotification.flags = Notification.FLAG_AUTO_CANCEL;

        if (NOTIFICATION_FLAG < 2000) {
            NOTIFICATION_FLAG++;
        } else {
            NOTIFICATION_FLAG = 1001;
        }

        LogUtils.i(TAG, "准备进行推送, title = " + title);
        mNotificationManager.notify(NOTIFICATION_FLAG, mNotification);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static Boolean openNotificationChannel(Context context, NotificationManager manager, String channelId) {
        //判断通知是否有打开
        if (!isNotificationEnabled(context)) {
            toNotifySetting(context, null);
            return false;
        }
        //判断渠道通知是否打开
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = manager.getNotificationChannel(channelId);
            if (null != channel && channel.getImportance() == NotificationManager.IMPORTANCE_NONE) {
                //没打开调往设置界面
                toNotifySetting(context, channel.getId());
                return false;
            }
        }

        return true;
    }

    /**
     * 手动打开应用通知
     */
    public static void toNotifySetting(Context context, String channelId) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //适配 8.0及8.0以上(8.0需要先打开应用通知,再打开渠道通知)
            if (TextUtils.isEmpty(channelId)) {
                intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
            } else {
                intent.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
                intent.putExtra(Settings.EXTRA_CHANNEL_ID, channelId);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//适配 5.0及5.0以上
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            intent.putExtra("app_package", context.getPackageName());
            intent.putExtra("app_uid", context.getApplicationInfo().uid);
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {// 适配 4.4及4.4以上
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else {
            intent.setAction(Settings.ACTION_SETTINGS);
        }
        context.startActivity(intent);
    }


    /**
     * 判断应用通知是否打开
     *
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static boolean isNotificationEnabled(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
            return notificationManagerCompat.areNotificationsEnabled();
        }
        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        try {
            Class  appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(
                    CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (Integer) opPostNotificationValue.get(Integer.class);

            return ( AppOpsManager.MODE_ALLOWED ==
                    (Integer)(checkOpNoThrowMethod.invoke(
                            mAppOps, value, context.getApplicationInfo().uid, context.getPackageName())));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 离线数据通知
     *
     * @param title
     * @param content
     * @param value
     */
    public void setOffMessageNotification(String title, String content, String value) {
        LogUtils.i(TAG, "setOffMessageNotification in ");
        Intent intent1 = new Intent();
        intent1.putExtra(GLLoginManager.ACCEPT_RECEIVER_TITLE, title);
        intent1.putExtra(GLLoginManager.ACCEPT_RECEIVER_CONTENT, content);
        intent1.putExtra(GLLoginManager.ACCEPT_RECEIVER_VALUE, value);
        intent1.putExtra(GLLoginManager.ACCEPT_RECEIVER_MSG_ID, "");
        intent1.setAction(GLLoginManager.ACCEPT_RECEIVER_OFF_MESSAGE_NOTIFICATION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String pakName = GLPushManager.getInstance().getMyContext().getPackageName();
            intent1.setComponent(new ComponentName(pakName, pakName + ".glpush.GLGetOffMessageReceiver"));
            GLPushManager.getInstance().getMyContext().sendBroadcast(intent1);
            LogUtils.i(TAG, "发送广播, intent1,pakName = " + pakName);
        } else {
            GLPushManager.getInstance().getMyContext().sendBroadcast(intent1);
        }

    }
}