1. 程式人生 > >獲取opp手機通知許可權

獲取opp手機通知許可權

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.RequiresApi; import android.support.v4.app.FragmentManager; import com.tiangui.customView.CustomDialog; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * 檔案描述:通知的許可權檢查類 * 作者:Created by BiJingCun on 2018/6/5.
*/ public class NotificationsUtils { private static final String CHECK_OP_NO_THROW = "checkOpNoThrow"; private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION"; public static boolean notificationIsOpen(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
) {//API19+ return notificationCheckFor19Up(context); } return false; } @RequiresApi(api = Build.VERSION_CODES.KITKAT) private static boolean notificationCheckFor19Up(Context context) { AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); ApplicationInfo applicationInfo = context.getApplicationInfo(); String pkg = context.getApplicationContext().getPackageName(); int uid = applicationInfo.uid; Class appOpsClass; try { 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 op = (int) opPostNotificationValue.get(Integer.class); return ((int) checkOpNoThrowMethod.invoke(appOpsManager, op, uid, pkg) == AppOpsManager.MODE_ALLOWED); } catch (Exception e) { e.printStackTrace(); } return true; } public interface NotificationCheckResultListener { void checkResult(boolean hasOpenNotification); } public static void checkNotificationOpend(final Activity context, NotificationCheckResultListener listener, boolean jump2Setting) { if (notificationIsOpen(context)) { if (null != listener) { listener.checkResult(true); } } else { if (jump2Setting) { //彈窗處理修改預設地址 new CustomDialog.Builder(context, 2) .setBody("溫馨提示:去開通通知狀態許可權") .setCancleText("取消") .setOKText("確定") .setOkOnClickListener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_SETTINGS); context.startActivity(intent); } }) .setCancleOnClickListener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).creatDialog().show(); } else { listener.checkResult(false); } } } }