下面列出了怎么用android.app.AppOpsManager的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private static boolean checkOps(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] = AppUtils.getAppPackageName();
int m = (Integer) method.invoke(object, arrayOfObject1);
return m == AppOpsManager.MODE_ALLOWED || !RomUtils.isDomesticSpecialRom();
} catch (Exception ignore) {
}
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);
break;
case R.id.action_close_all:
changeAll(AppOpsManager.MODE_IGNORED);
break;
case R.id.action_app_info:
startAppinfo();
break;
}
return super.onOptionsItemSelected(item);
}
private boolean clipboardAccessAllowed(int op, String callingPackage, int callingUid) {
// Check the AppOp.
if (mAppOps.noteOp(op, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
return false;
}
try {
// Installed apps can access the clipboard at any time.
if (!AppGlobals.getPackageManager().isInstantApp(callingPackage,
UserHandle.getUserId(callingUid))) {
return true;
}
// Instant apps can only access the clipboard if they are in the foreground.
return mAm.isAppForeground(callingUid);
} catch (RemoteException e) {
Slog.e("clipboard", "Failed to get Instant App status for package " + callingPackage,
e);
return false;
}
}
public static boolean checkOverlayPermission(Context context) {
AppOpsManager appOpsMgr = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
try {
if (appOpsMgr != null) {
int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window",
android.os.Process.myUid(), context.getPackageName());
if (mode == 0) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private boolean isOpRestrictedLocked(int uid, int code, String packageName) {
int userHandle = UserHandle.getUserId(uid);
final int restrictionSetCount = mOpUserRestrictions.size();
for (int i = 0; i < restrictionSetCount; i++) {
// For each client, check that the given op is not restricted, or that the given
// package is exempt from the restriction.
ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i);
if (restrictionState.hasRestriction(code, packageName, userHandle)) {
if (AppOpsManager.opAllowSystemBypassRestriction(code)) {
// If we are the system, bypass user restrictions for certain codes
synchronized (this) {
Ops ops = getOpsRawLocked(uid, packageName, true /* edit */,
false /* uidMismatchExpected */);
if ((ops != null) && ops.isPrivileged) {
return false;
}
}
}
return true;
}
}
return false;
}
private void checkPermissionCamera() {
int checkPermission = 0;
if (Build.VERSION.SDK_INT >= 23) {
// checkPermission =ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA);
checkPermission = PermissionChecker.checkSelfPermission(this, Manifest.permission.CAMERA);
if (checkPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
} else {
isOpenCamera = true;
}
} else {
checkPermission = checkPermission(26);
if (checkPermission == AppOpsManager.MODE_ALLOWED) {
isOpenCamera = true;
} else if (checkPermission == AppOpsManager.MODE_IGNORED) {
isOpenCamera = false;
displayFrameworkBugMessageAndExit();
}
}
}
@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(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;
}
private void checkPermissionCamera() {
int checkPermission = 0;
if (Build.VERSION.SDK_INT >= 23) {
// checkPermission =ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA);
checkPermission = PermissionChecker.checkSelfPermission(this, Manifest.permission.CAMERA);
if (checkPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
} else {
isOpenCamera = true;
}
} else {
checkPermission = checkPermission(26);
if (checkPermission == AppOpsManager.MODE_ALLOWED) {
isOpenCamera = true;
} else if (checkPermission == AppOpsManager.MODE_IGNORED) {
isOpenCamera = false;
displayFrameworkBugMessageAndExit();
}
}
}
@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.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;
}
private static boolean hasAppOpsPermission(
Context context, int callingUid, String callingPackage) {
if (callingPackage != null) {
AppOpsManager appOps = (AppOpsManager) context.getSystemService(
Context.APP_OPS_SERVICE);
final int mode = appOps.noteOp(AppOpsManager.OP_GET_USAGE_STATS,
callingUid, callingPackage);
if (mode == AppOpsManager.MODE_DEFAULT) {
// The default behavior here is to check if PackageManager has given the app
// permission.
final int permissionCheck = context.checkCallingPermission(
Manifest.permission.PACKAGE_USAGE_STATS);
return permissionCheck == PackageManager.PERMISSION_GRANTED;
}
return (mode == AppOpsManager.MODE_ALLOWED);
}
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 == 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(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;
}
/**
* Called when a wake lock is released.
*/
public void onWakeLockReleased(int flags, String tag, String packageName,
int ownerUid, int ownerPid, WorkSource workSource, String historyTag) {
if (DEBUG) {
Slog.d(TAG, "onWakeLockReleased: flags=" + flags + ", tag=\"" + tag
+ "\", packageName=" + packageName
+ ", ownerUid=" + ownerUid + ", ownerPid=" + ownerPid
+ ", workSource=" + workSource);
}
final int monitorType = getBatteryStatsWakeLockMonitorType(flags);
if (monitorType >= 0) {
try {
if (workSource != null) {
mBatteryStats.noteStopWakelockFromSource(workSource, ownerPid, tag,
historyTag, monitorType);
} else {
mBatteryStats.noteStopWakelock(ownerUid, ownerPid, tag,
historyTag, monitorType);
mAppOps.finishOp(AppOpsManager.OP_WAKE_LOCK, ownerUid, packageName);
}
} catch (RemoteException ex) {
// Ignore
}
}
}
@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;
}
@Override
public void putCache(String packageName, Uri key, Bundle value, int userId) {
Bundle.setDefusable(value, true);
enforceCrossUserPermission(userId, TAG);
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CACHE_CONTENT, TAG);
mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
packageName);
final String providerPackageName = getProviderPackageName(key);
final Pair<String, Uri> fullKey = Pair.create(packageName, key);
synchronized (mCache) {
final ArrayMap<Pair<String, Uri>, Bundle> cache = findOrCreateCacheLocked(userId,
providerPackageName);
if (value != null) {
cache.put(fullKey, value);
} else {
cache.remove(fullKey);
}
}
}
@Override
public Bundle getCache(String packageName, Uri key, int userId) {
enforceCrossUserPermission(userId, TAG);
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CACHE_CONTENT, TAG);
mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
packageName);
final String providerPackageName = getProviderPackageName(key);
final Pair<String, Uri> fullKey = Pair.create(packageName, key);
synchronized (mCache) {
final ArrayMap<Pair<String, Uri>, Bundle> cache = findOrCreateCacheLocked(userId,
providerPackageName);
return cache.get(fullKey);
}
}
public void systemReady() {
mAppOps = mContext.getSystemService(AppOpsManager.class);
synchronized (mSessions) {
readSessionsLocked();
reconcileStagesLocked(StorageManager.UUID_PRIVATE_INTERNAL, false /*isInstant*/);
reconcileStagesLocked(StorageManager.UUID_PRIVATE_INTERNAL, true /*isInstant*/);
final ArraySet<File> unclaimedIcons = newArraySet(
mSessionsDir.listFiles());
// Ignore stages and icons claimed by active sessions
for (int i = 0; i < mSessions.size(); i++) {
final PackageInstallerSession session = mSessions.valueAt(i);
unclaimedIcons.remove(buildAppIconFile(session.sessionId));
}
// Clean up orphaned icons
for (File icon : unclaimedIcons) {
Slog.w(TAG, "Deleting orphan icon " + icon);
icon.delete();
}
}
}
public static boolean isMockLocationEnabled(Context context) {
boolean isMockLocation = false;
try {
//if marshmallow
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
AppOpsManager opsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
if (opsManager != null) {
isMockLocation = (opsManager.checkOp(AppOpsManager.OPSTR_MOCK_LOCATION, android.os.Process.myUid(), context.getPackageName()) == 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 false;
}
return isMockLocation;
}
/**
* Check if application can draw over other apps
* @param context Context
* @return Boolean
*/
public static boolean canDrawOverlays(@NonNull Context context) {
final 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.
}
@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(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;
}
private void enforceTunnelPermissions(String callingPackage) {
checkNotNull(callingPackage, "Null calling package cannot create IpSec tunnels");
switch (getAppOpsManager().noteOp(
AppOpsManager.OP_MANAGE_IPSEC_TUNNELS,
Binder.getCallingUid(), callingPackage)) {
case AppOpsManager.MODE_DEFAULT:
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.MANAGE_IPSEC_TUNNELS, "IpSecService");
break;
case AppOpsManager.MODE_ALLOWED:
return;
default:
throw new SecurityException("Request to ignore AppOps for non-legacy API");
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private boolean hasUsageAccess() {
try {
PackageManager packageManager = getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
applicationInfo.uid, applicationInfo.packageName);
return (mode == AppOpsManager.MODE_ALLOWED);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
private int enforceWritePermission(Uri uri, IBinder callerToken)
throws SecurityException {
final int mode = enforceWritePermissionInner(uri, callerToken);
if (mode != MODE_ALLOWED) {
return mode;
}
return AppOpsManager.MODE_ALLOWED;
}
public static AlertDialog showRecentAppsDialog(Context context, Callbacks callbacks) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !isSystemApp(context)) {
ApplicationInfo applicationInfo = null;
try {
applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) { /* Gracefully fail */ }
if(applicationInfo != null) {
AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
if(mode != AppOpsManager.MODE_ALLOWED) {
AlertDialog.Builder builder;
if(hasAndroidTVSettings(context))
builder = buildRecentAppsDialogAndroidTV(context, callbacks);
else
builder = buildRecentAppsDialogStandard(context, callbacks);
AlertDialog dialog = builder.create();
dialog.show();
dialog.setCancelable(false);
return dialog;
}
}
}
callbacks.onFinish.run();
return null;
}
@Override
public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
uri = validateIncomingUri(uri);
uri = maybeGetUriWithoutUserId(uri);
if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
return 0;
}
final String original = setCallingPackage(callingPkg);
try {
return ContentProvider.this.delete(uri, selection, selectionArgs);
} finally {
setCallingPackage(original);
}
}