【发布时间】:2016-09-06 23:27:39
【问题描述】:
我想检查另一个应用是否已被授予“危险”或“系统”级别的权限。
我已尝试加载另一个应用程序的上下文并调用 packageContext.checkCallingPermission(permission)。但是,文档说它会返回
如果允许调用 pid/uid 获得该权限,则为 PERMISSION_GRANTED,如果不允许,则为 PERMISSION_DENIED。
是否可以检查其他应用是否已获得权限?
这是我的尝试(我在意识到它检查调用 pid/uid 并且似乎没有考虑上下文之前写了它):
void checkAllGrantedPermissions(Context context) {
PackageManager pm = context.getPackageManager();
// get all installed apps with info about what permissions they requested.
List<PackageInfo> packageInfos = pm.getInstalledPackages(PackageManager.GET_PERMISSIONS);
// Get the hidden method PermissionInfo#protectionToString(int) so we can log info about the requested permission
Method protectionToString;
try {
protectionToString = PermissionInfo.class.getDeclaredMethod("protectionToString", int.class);
if (!protectionToString.isAccessible()) protectionToString.setAccessible(true);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
// loop through all installed apps
for (PackageInfo packageInfo : packageInfos) {
if (packageInfo.requestedPermissions == null) {
// No permissions are requested in the AndroidManifest
continue;
}
String appName = packageInfo.applicationInfo.loadLabel(pm).toString();
String packageName = packageInfo.packageName;
// loop through all requested permissions in the AndroidManifest
for (String permission : packageInfo.requestedPermissions) {
PermissionInfo permissionInfo;
try {
permissionInfo = pm.getPermissionInfo(permission, 0);
} catch (PackageManager.NameNotFoundException e) {
Log.i(TAG, String.format("unknown permission '%s' found in '%s'", permission, packageName));
continue;
}
// convert the protectionLevel to a string (not necessary, but useful info)
String protLevel;
try {
protLevel = (String) protectionToString.invoke(null, permissionInfo.protectionLevel);
} catch (Exception ignored) {
protLevel = "????";
}
// Create the package's context to check if the package has the requested permission
Context packageContext;
try {
packageContext = context.createPackageContext(packageName, 0);
} catch (PackageManager.NameNotFoundException wtf) {
continue;
}
int ret = packageContext.checkCallingPermission(permission);
if (ret == PackageManager.PERMISSION_DENIED) {
Log.i(TAG, String.format("%s [%s] is denied permission %s (%s)",
appName, packageName, permission, protLevel));
} else {
Log.i(TAG, String.format("%s [%s] has granted permission %s (%s)",
appName, packageName, permission, protLevel));
}
}
}
}
【问题讨论】:
-
@adneal 谢谢!我还需要检查
REQUESTED_PERMISSION_REQUIRED标志。如果您将此作为答案发布,我会接受。
标签: android android-6.0-marshmallow android-permissions