下面列出了怎么用android.content.pm.PermissionInfo的API类实例代码及写法,或者点击链接到github查看源代码。
public PermissionInfo getPermissionInfo(String name, int flags) throws RemoteException {
waitForReadyInner();
try {
enforcePluginFileExists();
if (shouldNotBlockOtherInfo()) {
for (PluginPackageParser pluginPackageParser : this.mPluginCache.values()) {
for (PermissionInfo permissionInfo : pluginPackageParser.getPermissions()) {
if (TextUtils.equals(permissionInfo.name, name)) {
return permissionInfo;
}
}
}
}
List<String> pkgs = this.mActivityManagerService.getPackageNamesByPid(Binder.getCallingPid());
for (PluginPackageParser pluginPackageParser2 : this.mPluginCache.values()) {
for (PermissionInfo permissionInfo2 : pluginPackageParser2.getPermissions()) {
if (TextUtils.equals(permissionInfo2.name, name) && pkgs.contains(permissionInfo2.packageName)) {
return permissionInfo2;
}
}
}
} catch (Exception e) {
handleException(e);
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public List<PermissionInfo> queryPermissionsByGroup(String group, int flags)
throws NameNotFoundException {
try {
ParceledListSlice<PermissionInfo> parceledList =
mPM.queryPermissionsByGroup(group, flags);
if (parceledList != null) {
List<PermissionInfo> pi = parceledList.getList();
if (pi != null) {
return pi;
}
}
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
throw new NameNotFoundException(group);
}
@Test
public void ensureRequiredPermissions_ifPermissionIsDangerousAndPermissionGrantStateIsAlreadySet_shouldReturnTrue() {
addPermissionInfo(DANGEROUS_PERMISSION, PermissionInfo.PROTECTION_DANGEROUS);
shadowOf(mDevicePolicyManager).setProfileOwner(TESTDPC_ADMIN);
mDevicePolicyManager.setPermissionGrantState(
TESTDPC_ADMIN,
mContext.getPackageName(),
DANGEROUS_PERMISSION,
DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED);
boolean requiredPermissionsGranted = PermissionsHelper
.ensureRequiredPermissions(new String[]{DANGEROUS_PERMISSION}, TESTDPC_ADMIN, mContext);
assertTrue(requiredPermissionsGranted);
assertThat(mDevicePolicyManager
.getPermissionGrantState(TESTDPC_ADMIN, mContext.getPackageName(), DANGEROUS_PERMISSION))
.isEqualTo(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED);
}
@TargetApi(23)
private boolean isDisplayablePermission(PermissionInfo pInfo, int existingReqFlags) {
final int base = pInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
final boolean isNormal = base == PermissionInfo.PROTECTION_NORMAL;
final boolean isDangerous = base == PermissionInfo.PROTECTION_DANGEROUS
|| ((pInfo.protectionLevel & PermissionInfo.PROTECTION_FLAG_PRE23) != 0);
// Dangerous and normal permissions are always shown to the user
// this is matches the permission list in AppDetailsActivity
if (isNormal || isDangerous) {
return true;
}
final boolean isDevelopment = (pInfo.protectionLevel & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0;
final boolean wasGranted = (existingReqFlags & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0;
// Development permissions are only shown to the user if they are already
// granted to the app -- if we are installing an app and they are not
// already granted, they will not be granted as part of the install.
return isDevelopment && wasGranted;
}
private void doPermissionCheck(Context context, ResultCollector collector, final String permission) {
PackageManager pm = context.getPackageManager();
try {
PermissionInfo info = pm.getPermissionInfo(permission, 0);
PermissionGroupInfo groupInfo = info.group != null ? pm.getPermissionGroupInfo(info.group, 0) : null;
CharSequence permLabel = info.loadLabel(pm);
CharSequence groupLabel = groupInfo != null ? groupInfo.loadLabel(pm) : permLabel;
collector.addResult(context.getString(R.string.self_check_name_permission, permLabel),
context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED ? Positive : Negative,
context.getString(R.string.self_check_resolution_permission, groupLabel),
new SelfCheckGroup.CheckResolver() {
@Override
public void tryResolve(Fragment fragment) {
fragment.requestPermissions(new String[]{permission}, 0);
}
});
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, e);
}
}
static void hasDefinePermission(Context context) {
try {
String packName = context.getPackageName();
String perm = packName.concat(".permission.ONE_KEY_PERM");
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
if (pi.permissions == null) {
log(packName);
return;
}
for (PermissionInfo permission : pi.permissions) {
if (perm.equals(permission.name)
&& permission.protectionLevel == PROTECTION_SIGNATURE
&& ContextCompat.checkSelfPermission(context, perm) == PackageManager.PERMISSION_GRANTED) {
return;
}
}
log(packName);
} catch (Exception e) {
e.printStackTrace();
}
}
public void updateDynamicPermission(Collection<BasePermission> permissionTrees) {
if (PackageManagerService.DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
+ getName() + " pkg=" + getSourcePackageName()
+ " info=" + pendingPermissionInfo);
if (sourcePackageSetting == null && pendingPermissionInfo != null) {
final BasePermission tree = findPermissionTree(permissionTrees, name);
if (tree != null && tree.perm != null) {
sourcePackageSetting = tree.sourcePackageSetting;
perm = new PackageParser.Permission(tree.perm.owner,
new PermissionInfo(pendingPermissionInfo));
perm.info.packageName = tree.perm.info.packageName;
perm.info.name = name;
uid = tree.uid;
}
}
}
private PermissionInfo getPermissionInfo(String permName, String packageName, int flags,
int callingUid) {
if (mPackageManagerInt.getInstantAppPackageName(callingUid) != null) {
return null;
}
// reader
synchronized (mLock) {
final BasePermission bp = mSettings.getPermissionLocked(permName);
if (bp == null) {
return null;
}
final int adjustedProtectionLevel = adjustPermissionProtectionFlagsLocked(
bp.getProtectionLevel(), packageName, callingUid);
return bp.generatePermissionInfo(adjustedProtectionLevel, flags);
}
}
/**
* Return true if all given permissions are signature-only perms.
*/
final boolean isSignaturePerm(String[] perms) {
if (perms == null) {
return false;
}
IPackageManager pm = AppGlobals.getPackageManager();
for (int i = perms.length-1; i >= 0; i--) {
try {
PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0);
if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE
| PermissionInfo.PROTECTION_FLAG_PRIVILEGED))
!= PermissionInfo.PROTECTION_SIGNATURE) {
// If this a signature permission and NOT allowed for privileged apps, it
// is okay... otherwise, nope!
return false;
}
} catch (RemoteException e) {
return false;
}
}
return true;
}
@Override
public PermissionInfo getPermissionInfo(String name, int flags)
throws NameNotFoundException {
try {
PermissionInfo pi = mPM.getPermissionInfo(name, flags);
if (pi != null) {
return pi;
}
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
throw new NameNotFoundException(name);
}
private void askForPermission() {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
String name;
try {
PackageManager pm = getPackageManager();
PermissionInfo permissionInfo = pm.getPermissionInfo(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.GET_META_DATA);
name = (String) permissionInfo.loadLabel(pm);
} catch (PackageManager.NameNotFoundException e) {
logger.error("Failed to obtain name for permission", e);
name = "read external storage";
}
new AlertDialog.Builder(this)
.setMessage(getString(R.string.msgWriteExternalStorageRationale, name))
.setPositiveButton(R.string.ok, (dialog, which) -> requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE))
.setNegativeButton(R.string.cancel, (dialog, which) -> finish())
.create()
.show();
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
} else {
mDataMoveFragment.startDataMove();
}
}
@Override
public boolean addPermission(PermissionInfo info) {
try {
return mPM.addPermission(info);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public boolean addPermissionAsync(PermissionInfo info) {
try {
return mPM.addPermissionAsync(info);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public boolean addPermission(PermissionInfo info) {
try {
return mPM.addPermission(info);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public boolean addPermissionAsync(PermissionInfo info) {
try {
return mPM.addPermissionAsync(info);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
@Override
public PermissionInfo getPermissionInfo(String name, int flags)
throws NameNotFoundException {
try {
PermissionInfo pi = mPM.getPermissionInfo(name, flags);
if (pi != null) {
return pi;
}
} catch (RemoteException e) {
throw new RuntimeException("Package manager has died", e);
}
throw new NameNotFoundException(name);
}
@Override
public List<PermissionInfo> queryPermissionsByGroup(String group, int flags)
throws NameNotFoundException {
try {
List<PermissionInfo> pi = mPM.queryPermissionsByGroup(group, flags);
if (pi != null) {
return pi;
}
} catch (RemoteException e) {
throw new RuntimeException("Package manager has died", e);
}
throw new NameNotFoundException(group);
}
@Override
public boolean addPermission(PermissionInfo info) {
try {
return mPM.addPermission(info);
} catch (RemoteException e) {
throw new RuntimeException("Package manager has died", e);
}
}
private static OpEntryInfo opEntry2Info(OpEntry op, Context context, PackageManager pm) {
OpEntryInfo opEntryInfo = new OpEntryInfo(op);
if (OtherOp.isOtherOp(op.getOp())) {
opEntryInfo.opName = OtherOp.getOpName(op.getOp());
opEntryInfo.opPermsName = OtherOp.getOpPermName(op.getOp());
}
if (opEntryInfo.opName != null) {
try {
if (!OtherOp.isOtherOp(op.getOp())) {
PermissionInfo permissionInfo = pm.getPermissionInfo(opEntryInfo.opPermsName, 0);
opEntryInfo.opPermsLab = String.valueOf(permissionInfo.loadLabel(pm));
opEntryInfo.opPermsDesc = String.valueOf(permissionInfo.loadDescription(pm));
}
} catch (PackageManager.NameNotFoundException e) {
//ignore
}
if (opEntryInfo.opPermsLab == null) {
Integer resId = sPermI18N.get(opEntryInfo.opName);
if (resId != null) {
opEntryInfo.opPermsLab = context.getString(resId);
opEntryInfo.opPermsDesc = opEntryInfo.opName;
}
}
return opEntryInfo;
}
return null;
}
@Override
public PermissionInfo generatePermissionInfo(
Object permission, int flags) throws Exception {
/*public static final PermissionInfo generatePermissionInfo(
Permission p, int flags)*/
Method method = MethodUtils.getAccessibleMethod(sPackageParserClass, "generatePermissionInfo", sPermissionClass, int.class);
return (PermissionInfo) method.invoke(null, permission, flags);
}
private boolean isDisplayablePermission(PermissionInfo pInfo, int newReqFlags,
int existingReqFlags) {
final int base = pInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
final boolean isNormal = (base == PermissionInfo.PROTECTION_NORMAL);
// We do not show normal permissions in the UI.
if (isNormal) {
return false;
}
final boolean isDangerous = (base == PermissionInfo.PROTECTION_DANGEROUS)
|| ((pInfo.protectionLevel&PermissionInfo.PROTECTION_FLAG_PRE23) != 0);
final boolean isRequired =
((newReqFlags&PackageInfo.REQUESTED_PERMISSION_REQUIRED) != 0);
final boolean isDevelopment =
((pInfo.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
final boolean wasGranted =
((existingReqFlags&PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0);
final boolean isGranted =
((newReqFlags&PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0);
// Dangerous and normal permissions are always shown to the user if the permission
// is required, or it was previously granted
if (isDangerous && (isRequired || wasGranted || isGranted)) {
return true;
}
// Development permissions are only shown to the user if they are already
// granted to the app -- if we are installing an app and they are not
// already granted, they will not be granted as part of the install.
if (isDevelopment && wasGranted) {
if (localLOGV) Log.i(TAG, "Special perm " + pInfo.name
+ ": protlevel=0x" + Integer.toHexString(pInfo.protectionLevel));
return true;
}
return false;
}
@Override
public PermissionInfo generatePermissionInfo(
Object permission, int flags) throws Exception {
/* public static final PermissionInfo generatePermissionInfo(
Permission p, int flags) */
return super.generatePermissionInfo(permission, flags);
}
@Override
public List<PermissionInfo> queryPermissionsByGroup(String group, int flags)
throws NameNotFoundException {
try {
List<PermissionInfo> pi = mPM.queryPermissionsByGroup(group, flags);
if (pi != null) {
return pi;
}
} catch (RemoteException e) {
throw new RuntimeException("Package manager has died", e);
}
throw new NameNotFoundException(group);
}
@Override
public boolean addPermissionAsync(PermissionInfo info) {
try {
return mPM.addPermissionAsync(info);
} catch (RemoteException e) {
throw new RuntimeException("Package manager has died", e);
}
}
private static boolean isPermissionDangerous(String permission, Context context) {
PermissionInfo permissionInfo;
try {
permissionInfo = context.getPackageManager().getPermissionInfo(permission, 0);
} catch (NameNotFoundException e) {
Log.e(TAG, "Failed to look up permission.", e);
return false;
}
return permissionInfo != null
&& (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
== PermissionInfo.PROTECTION_DANGEROUS;
}
@Override
public boolean addPermission(PermissionInfo info) {
try {
return mPM.addPermission(info);
} catch (RemoteException e) {
throw new RuntimeException("Package manager has died", e);
}
}
@Override
public boolean addPermissionAsync(PermissionInfo info) {
try {
return mPM.addPermissionAsync(info);
} catch (RemoteException e) {
throw new RuntimeException("Package manager has died", e);
}
}
@Test
public void ensureRequiredPermissions_ifAtLeastOnePermissionNotGranted_shouldReturnFalse() {
addPermissionInfo(NORMAL_PERMISSION, PermissionInfo.PROTECTION_NORMAL);
addPermissionInfo(DANGEROUS_PERMISSION, PermissionInfo.PROTECTION_DANGEROUS);
shadowOf(mDevicePolicyManager).setProfileOwner(NON_TESTDPC_ADMIN);
boolean requiredPermissionsGranted = PermissionsHelper
.ensureRequiredPermissions(new String[]{NORMAL_PERMISSION, DANGEROUS_PERMISSION},
NON_TESTDPC_ADMIN, mContext);
assertFalse(requiredPermissionsGranted);
}
@Override
public boolean addPermission(PermissionInfo info) {
try {
return mPM.addPermission(info);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Check if the installed Gmail app supports querying for label information.
*
* @param c an application Context
* @return true if it's safe to make label API queries
*/
public static boolean canReadLabels(Context c) {
boolean supported = false;
try {
final PackageInfo info = c.getPackageManager().getPackageInfo(PACKAGE,
PackageManager.GET_PROVIDERS | PackageManager.GET_PERMISSIONS);
boolean allowRead = false;
if (info.permissions != null) {
for (int i = 0, len = info.permissions.length; i < len; i++) {
final PermissionInfo perm = info.permissions[i];
if (PERMISSION.equals(perm.name)
&& perm.protectionLevel < PermissionInfo.PROTECTION_SIGNATURE) {
allowRead = true;
break;
}
}
}
if (allowRead && info.providers != null) {
for (int i = 0, len = info.providers.length; i < len; i++) {
final ProviderInfo provider = info.providers[i];
if (AUTHORITY.equals(provider.authority) &&
TextUtils.equals(PERMISSION, provider.readPermission)) {
supported = true;
}
}
}
} catch (NameNotFoundException e) {
// Gmail app not found
}
return supported;
}