@TargetApi(19) private static boolean checkOp(Context context, int op) { final int version = Build.VERSION.SDK_INT; if (version >= Build.VERSION_CODES.KITKAT) { AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Method method = manager.getClass().getDeclaredMethod("checkOp", int.class, int.class, String.class); int property = (Integer) method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName()); return AppOpsManager.MODE_ALLOWED == property; } catch (Exception e) { e.printStackTrace(); } } return false; }
public static boolean usagePermissionCheck(Context context) { boolean granted = false; if (context != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try { AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), context.getPackageName()); if (mode == AppOpsManager.MODE_DEFAULT) { String permissionUsage = "android.permission.PACKAGE_USAGE_STATS"; granted = (context.checkCallingOrSelfPermission(permissionUsage) == PackageManager.PERMISSION_GRANTED); } else { granted = (mode == AppOpsManager.MODE_ALLOWED); } } catch (Throwable e) { } } return granted; }
public static boolean checkAlertWindowsPermission(Context context) { try { Object object = context.getSystemService(Context.APP_OPS_SERVICE); if (object == null) { return false; } Class localClass = object.getClass(); Class[] arrayOfClass = new Class[3]; arrayOfClass[0] = Integer.TYPE; arrayOfClass[1] = Integer.TYPE; arrayOfClass[2] = String.class; Method method = localClass.getMethod("checkOp", arrayOfClass); if (method == null) { return false; } Object[] arrayOfObject1 = new Object[3]; arrayOfObject1[0] = 24; arrayOfObject1[1] = Binder.getCallingUid(); arrayOfObject1[2] = context.getPackageName(); int m = ((Integer) method.invoke(object, arrayOfObject1)); return m == AppOpsManager.MODE_ALLOWED; } catch (Exception ex) { } return false; }
@TargetApi(Build.VERSION_CODES.KITKAT) private static boolean checkOp(Context context, int op) { final int version = Build.VERSION.SDK_INT; if (version >= 19) { AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Class clazz = AppOpsManager.class; Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class); return AppOpsManager.MODE_ALLOWED == (int)method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName()); } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } } else { Log.e(TAG, "Below API 19 cannot invoke!"); } return false; }
@TargetApi(Build.VERSION_CODES.KITKAT) private static boolean checkOp(Context context, int op) { final int version = Build.VERSION.SDK_INT; if (version >= 19) { AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Class clazz = AppOpsManager.class; Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class); return AppOpsManager.MODE_ALLOWED == (int) method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName()); } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } } else { Log.e(TAG, "Below API 19 cannot invoke!"); } return false; }
@TargetApi(Build.VERSION_CODES.KITKAT) private static boolean checkOp(Context context, int op) { final int version = Build.VERSION.SDK_INT; if (version >= 19) { AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Class clazz = AppOpsManager.class; Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class); return AppOpsManager.MODE_ALLOWED == (int)method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName()); } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } } else { Log.e("", "Below API 19 cannot invoke!"); } return false; }
@TargetApi(19) private static boolean checkOp(Context context, int op) { final int version = Build.VERSION.SDK_INT; if (version >= Build.VERSION_CODES.KITKAT) { AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Method method = manager.getClass().getDeclaredMethod("checkOp", int.class, int.class, String.class); int property = (Integer) method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName()); return AppOpsManager.MODE_ALLOWED == property; } catch (Exception e) { e.printStackTrace(); } } else { } return false; }
/** * Check if the calling context has a set of permissions. * * @param context The calling context * @param permissions One or more permission. * @return True if all permissions are already granted, false if at least one permission is not * yet granted. * @see android.Manifest.permission */ public static boolean hasPermissions(@NonNull Context context, @NonNull @Size(min = 1) String... permissions) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } final AppOpsManager appOpsManager = context.getSystemService(AppOpsManager.class); final String packageName = context.getPackageName(); for (String permission : permissions) { if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } String op = AppOpsManager.permissionToOp(permission); if (!TextUtils.isEmpty(op) && appOpsManager != null && appOpsManager.noteProxyOp(op, packageName) != AppOpsManager.MODE_ALLOWED) { return false; } } return true; }
/** * 判断是否有用权限 * * @param context 上下文参数 */ @TargetApi(Build.VERSION_CODES.KITKAT) private static boolean HavaPermissionForTest(Context context) { try { PackageManager packageManager = context.getPackageManager(); ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0); AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); int mode = 0; if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName); } return (mode == AppOpsManager.MODE_ALLOWED); } catch (PackageManager.NameNotFoundException e) { return true; } }
private boolean isMockLocationEnabled() { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { AppOpsManager opsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); return (opsManager.checkOp(AppOpsManager.OPSTR_MOCK_LOCATION, android.os.Process.myUid(), BuildConfig.APPLICATION_ID) == AppOpsManager.MODE_ALLOWED); } else { String mockLocationSettingValue = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION); return (mockLocationSettingValue.equals(ENABLED_MOCK_LOCATION_VALUE)); } } catch (SecurityException e) { return false; } }
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.action_reset: mPresenter.reset(); return true; case R.id.action_hide_perm: showHidePerms(); return true; case R.id.action_open_all: changeAll(AppOpsManager.MODE_ALLOWED); ATracker.send(AEvent.C_APP_OPEN_ALL); break; case R.id.action_close_all: changeAll(AppOpsManager.MODE_IGNORED); ATracker.send(AEvent.C_APP_IGNOR_ALL); break; case R.id.action_app_info: startAppinfo(); break; } return super.onOptionsItemSelected(item); }
public OpsResult disableAllPermission(final String packageName) throws Exception { OpsResult opsForPackage = getOpsForPackage(packageName); if (opsForPackage != null) { if (opsForPackage.getException() == null) { List<PackageOps> list = opsForPackage.getList(); if (list != null && !list.isEmpty()) { for (PackageOps packageOps : list) { List<OpEntry> ops = packageOps.getOps(); if (ops != null) { for (OpEntry op : ops) { if (op.getMode() != AppOpsManager.MODE_IGNORED) { setOpsMode(packageName, op.getOp(), AppOpsManager.MODE_IGNORED); } } } } } } else { throw new Exception(opsForPackage.getException()); } } return opsForPackage; }
static int permissionToCode(String permission) { if (sRuntimePermToOp == null) { sRuntimePermToOp = new HashMap<>(); Object sOpPerms = ReflectUtils.getFieldValue(AppOpsManager.class, "sOpPerms"); Object sOpToSwitch = ReflectUtils.getFieldValue(AppOpsManager.class, "sOpToSwitch"); if (sOpPerms instanceof String[] && sOpToSwitch instanceof int[]) { String[] opPerms = (String[]) sOpPerms; int[] opToSwitch = (int[]) sOpToSwitch; if (opPerms.length == opToSwitch.length) { for (int i = 0; i < opToSwitch.length; i++) { if (opPerms[i] != null) { sRuntimePermToOp.put(opPerms[i], opToSwitch[i]); } } } } } Integer code = sRuntimePermToOp.get(permission); if (code != null) { return code; } return -1; }
/** * 判断是否开启浮窗权限 * @return */ public static int hasAuthorFloatWin(Context context){ if (DeviceInfoUtil.getSystemVersion() < 19){ return NOT_SUPPORT_AUTHOR; } try { AppOpsManager appOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE); Class c = appOps.getClass(); Class[] cArg = new Class[3]; cArg[0] = int.class; cArg[1] = int.class; cArg[2] = String.class; Method lMethod = c.getDeclaredMethod("checkOp", cArg); if (AppOpsManager.MODE_ALLOWED == (Integer) lMethod.invoke(appOps, 24, Binder.getCallingUid(), context.getPackageName())){ return HAS_AUTHOR; } else { return NOT_AUTHOR; } } catch(Exception e) { return NOT_SUPPORT_AUTHOR; } }
public static boolean isPermissionGranted(@NonNull Context context) { if(!"Xiaomi".equalsIgnoreCase(Build.MANUFACTURER)) { return true; } if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Method method = manager.getClass().getDeclaredMethod("checkOp", int.class, int.class, String.class); int property = (Integer) method.invoke(manager, 24/*AppOpsManager.OP_SYSTEM_ALERT_WINDOW*/, Binder.getCallingUid(), context.getApplicationContext().getPackageName()); return AppOpsManager.MODE_ALLOWED == property; }catch (Throwable e) { WXLogUtils.e(TAG,e.getMessage()); return true; } } else { return true; } }
/** * "Xiaomi" phone is different others,need add AppOpsManager * @param context * @param permission * @return */ @TargetApi(23) private static boolean checkSelfPermissionForXiaomi(Context context, String permission) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { try { return checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED; } catch (RuntimeException t) { return false; } } int auth = ActivityCompat.checkSelfPermission(context, permission); AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); int checkOp = appOpsManager.checkOp(AppOpsManager.permissionToOp(permission), Process.myUid(), context.getPackageName()); if (auth == PackageManager.PERMISSION_GRANTED && checkOp == AppOpsManager.MODE_ALLOWED) { return true; } if (auth == PackageManager.PERMISSION_GRANTED && checkOp == AppOpsManager.MODE_IGNORED) { return false; } return false; }
public static boolean isNotificationEnabled(Context context) { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); ApplicationInfo appInfo = context.getApplicationInfo(); String pkg = context.getApplicationContext().getPackageName(); int uid = appInfo.uid; Class appOpsClass = null; /* Context.APP_OPS_MANAGER */ 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 = (int) opPostNotificationValue.get(Integer.class); return ((int) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED); } } catch (Exception e) { } return true; }
private static boolean setMode(Context context, int op, boolean allowed) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return false; } AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Method method = AppOpsManager.class.getDeclaredMethod("setMode", int.class, int.class, String.class, int.class); method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName(), allowed ? AppOpsManager.MODE_ALLOWED : AppOpsManager .MODE_IGNORED); return true; } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } return false; }
/** * 是否禁用某项操作 */ @TargetApi(Build.VERSION_CODES.KITKAT) public static boolean isAllowed(Context context, int op) { Log.d(TAG, "api level: " + Build.VERSION.SDK_INT); if (Build.VERSION.SDK_INT < 19) { return true; } Log.d(TAG, "op is " + op); String packageName = context.getApplicationContext().getPackageName(); AppOpsManager aom = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); Class<?>[] types = new Class[]{int.class, int.class, String.class}; Object[] args = new Object[]{op, Binder.getCallingUid(), packageName}; try { Method method = aom.getClass().getDeclaredMethod("checkOpNoThrow", types); Object mode = method.invoke(aom, args); Log.d(TAG, "invoke checkOpNoThrow: " + mode); if ((mode instanceof Integer) && ((Integer) mode == AppOpsManager.MODE_ALLOWED)) { Log.d(TAG, "allowed"); return true; } } catch (Exception e) { Log.e(TAG, "invoke error: " + e); e.printStackTrace(); } return false; }
/** * Check if application can draw over other apps * @param context Context * @return Boolean */ public static boolean canDrawOverlays(Context context) { int sdkInt = Build.VERSION.SDK_INT; if (sdkInt >= Build.VERSION_CODES.M) { if (sdkInt == Build.VERSION_CODES.O) { // Sometimes Settings.canDrawOverlays returns false after allowing permission. // Google Issue Tracker: https://issuetracker.google.com/issues/66072795 AppOpsManager appOpsMgr = context.getSystemService(AppOpsManager.class); if (appOpsMgr != null) { int mode = appOpsMgr.checkOpNoThrow( "android:system_alert_window", android.os.Process.myUid(), context.getPackageName() ); return mode == AppOpsManager.MODE_ALLOWED || mode == AppOpsManager.MODE_IGNORED; } else { return false; } } // Default return android.provider.Settings.canDrawOverlays(context); } return true; // This fallback may returns a incorrect result. }
@SuppressLint("NewApi") public static void enableWriteSmsOpt(Context mContext) { if (Build.VERSION.SDK_INT >= 19) { // Android 4.4 // 及以上才有以下功能,并且可直接设置程序有写短信权限,如果以下运行有异常,则表示可能系统为Android5.0 String PHONE_PACKAGE_NAME = mContext.getPackageName(); PackageManager packageManager = mContext.getPackageManager(); AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE); try { PackageInfo info = packageManager.getPackageInfo(PHONE_PACKAGE_NAME, 0); Field field = AppOpsManager.class.getDeclaredField("OP_WRITE_SMS"); int WRITE_SMS = field.getInt(appOps);// 写短信权限 Method method = AppOpsManager.class.getMethod("setMode", int.class, int.class, String.class, int.class); method.invoke(appOps, WRITE_SMS, info.applicationInfo.uid, PHONE_PACKAGE_NAME, AppOpsManager.MODE_ALLOWED); } catch (Exception ex) { // 表明该系统可能为Android5.0,且需要将程序设置成默认的短信程序 } } }
@TargetApi(Build.VERSION_CODES.KITKAT) public static boolean checkOp(Context context, int op) { final int version = Build.VERSION.SDK_INT; if (version >= 19) { AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Method method = manager.getClass().getDeclaredMethod("checkOp", int.class, int.class, String.class); int property = (Integer) method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName()); if (AppOpsManager.MODE_ALLOWED == property) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); } } else { Log.e(TAG, "Below API 19 cannot invoke!"); } return false; }
/** * Проверка наличия установленного флага "Показывать уведомления" в настройках приложения<br/> * Используется для версий ОС Android от 4.3 (android sdk api 19) * * @param context текущий контекст * @return true - если флаг установлен */ public static boolean isNotificationEnabled(Context context) { boolean result = false; if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); ApplicationInfo appInfo = context.getApplicationInfo(); String pkg = context.getApplicationContext().getPackageName(); int uid = appInfo.uid; Class appOpsClass = null; 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 value = (int) opPostNotificationValue.get(Integer.class); result = (int) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED; } catch (Exception ignored) { } } return result; }
public boolean isMockLocationSet() { boolean isMockLocation = false; try { //if marshmallow if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { AppOpsManager opsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); isMockLocation = (opsManager.checkOp(AppOpsManager.OPSTR_MOCK_LOCATION, android.os.Process.myUid(), BuildConfig.APPLICATION_ID) == AppOpsManager.MODE_ALLOWED); } else { // in marshmallow this will always return true isMockLocation = !android.provider.Settings.Secure.getString(context.getContentResolver(), "mock_location").equals("0"); } } catch (Exception e) { return isMockLocation; } Logger.d("MockLocation is enable?:%s", isMockLocation); return isMockLocation; }
@TargetApi(Build.VERSION_CODES.KITKAT) private static boolean checkOp(Context context, int op) { final int version = Build.VERSION.SDK_INT; if (version >= 19) { AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Class clazz = AppOpsManager.class; Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class); return AppOpsManager.MODE_ALLOWED == method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName()); } catch (Exception e) { Log.e("", e.getMessage()); } } else { Log.e("", "Below API 19 cannot invoke!"); } return false; }
@TargetApi(Build.VERSION_CODES.M) @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) { if (Settings.canDrawOverlays(this)) { if (checkUsagePermission()) { Intent intent = new Intent(this, BackgroundDetectService.class); startService(intent); } } } else if (requestCode == 2) { AppOpsManager appOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE); int mode = 0; mode = appOps.checkOpNoThrow("android:get_usage_stats", android.os.Process.myUid(), getPackageName()); boolean granted = mode == AppOpsManager.MODE_ALLOWED; if (!granted) { Toast.makeText(this, "请开启该权限", Toast.LENGTH_SHORT).show(); } } }