权限分类
-
Normal permissions
只需要在AndroidManifest.xml 中声明,如INTERNET,WAKE_LOCK等
-
Signature permissions
申请该权限的应用和定义该权限的应用有相同签名时,这个权限才会被授予,一些Signature permissions不能被三方应用使用
-
Dangerous permissions
需要申请运行时权限
Special permissions
如SYSTEM_ALERT_WINDOW需要应用发送Settings.ACTION_MANAGE_OVERLAY_PERMISSION intent去提示用户是否开启该权限
权限列表可以参考官网:
https://developer.android.google.cn/guide/topics/permissions/overview?hl=en
代码中的权限列表:
frameworks/base/data/etc/platform.xml
权限类型定义protectionLevel:
frameworks/base/core/res/AndroidManifest.xml
运行时权限申请方法
AndroidMenifest.xml 中添加
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
代码中添加:
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_SDCARD);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_SDCARD: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
... ...
} else {
... ...
}
return;
}
}
}
查看应用是否有运行时权限:
adb shell dumpsys package + 包名
Packages:
Package [com.example.hellojni2] (11f567c):
userId=10127
pkg=Package{714cb29 com.example.hellojni2}
... ...
requested permissions:
android.permission.WRITE_SETTINGS
android.permission.READ_EXTERNAL_STORAGE
android.permission.WRITE_EXTERNAL_STORAGE
User 0: ceDataInode=-4294761261 installed=true hidden=false suspended=false stopped=false notLaunched=false enabled=0 instant=false virtual=false
runtime permissions:
android.permission.READ_EXTERNAL_STORAGE: granted=true
android.permission.WRITE_EXTERNAL_STORAGE: granted=true
查看应用进程是否有某个权限,比如进程mediacodec,pid: 564是否有sdcard_rw权限
A3A_10_4G:/ $ cd proc/564
A3A_10_4G:/proc/564 $ cat status
Name: omx@1.0-service
State: S (sleeping)
Tgid: 564
Ngid: 0
Pid: 564
PPid: 1
TracerPid: 0
Uid: 1046 1046 1046 1046
Gid: 1006 1006 1006 1006
FDSize: 256
Groups: 1000 1005 1013 1015 1023 1026 1028 1031 3001 3002 3003 3007
id sdcard_rw
A3A_10_4G:/ $ id sdcard_rw
uid=1015(sdcard_rw) gid=1015(sdcard_rw) groups=1015(sdcard_rw), context=u:r:shell:s0
可以看到有1015权限,即SDCard读写错误
运行时权限申请流程
1. 显示权限申请Dialog
frameworks/support/compat/src/main/java/androidx/core/app/ActivityCompat.java
public static void requestPermissions(final @NonNull Activity activity,
final @NonNull String[] permissions, final @IntRange(from = 0) int requestCode) {
... ...
if (Build.VERSION.SDK_INT >= 23) {
activity.requestPermissions(permissions, requestCode);
}
... ...
}
打开全透明GrantPermissionsActivity
public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
... ...
//没有申请过权限弹出权限申请dialog
Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
mHasCurrentPermissionsRequest = true;
}
GrantPermissionsActivity实现接口GrantPermissionsViewHandler.ResultListener,用户点击允许添加权限时,回调 onPermissionGrantResult
@Override
public void onPermissionGrantResult(String name, boolean granted, boolean doNotAskAgain) {
... ...
GroupState groupState = mRequestGrantPermissionGroups.get(name);
if (groupState != null && groupState.mGroup != null) {
if (granted) {
//如果允许将整个权限组权限设为STATE_ALLOWED
groupState.mGroup.grantRuntimePermissions(doNotAskAgain,
groupState.affectedPermissions);
groupState.mState = GroupState.STATE_ALLOWED;
} else {
... ...
}
2. 最终调用到PMS的grantRuntimePermission更新权限
frameworks/base/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
private void grantRuntimePermission(String permName, String packageName, boolean overridePolicy,
int callingUid, final int userId, PermissionCallback callback) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
"grantRuntimePermission");
enforceCrossUserPermission(callingUid, userId,
true, // requireFullPermission
true, // checkShell
false, // requirePermissionWhenSameUser
"grantRuntimePermission");
final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName);
if (pkg == null || pkg.mExtras == null) {
throw new IllegalArgumentException("Unknown package: " + packageName);
}
final BasePermission bp;
synchronized(mLock) {
bp = mSettings.getPermissionLocked(permName);
}
... ...
//检查AndroidManifest.xml中是否有声明过权限,如果没有抛出SecurityException异常
bp.enforceDeclaredUsedAndRuntimeOrDevelopment(pkg);
final int uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
final PackageSetting ps = (PackageSetting) pkg.mExtras;
final PermissionsState permissionsState = ps.getPermissionsState();
?。÷砸恍┒园姹竞腿ㄏ蘩嘈图觳? ... ...
final int result = permissionsState.grantRuntimePermission(bp, userId);
switch (result) {
case PermissionsState.PERMISSION_OPERATION_FAILURE: {
return;
}
case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
if (callback != null) {
callback.onGidsChanged(UserHandle.getAppId(pkg.applicationInfo.uid), userId);
}
}
break;
}
//存在runtime-permissions.xml中
if (callback != null) {
callback.onPermissionGranted(uid, userId);
}
... ...
}
3.权限信息存储
frameworks/base/services/core/java/com/android/server/pm/permission/PermissionsState.java
private int grantPermission(BasePermission permission, int userId) {
if (hasPermission(permission.getName(), userId)) {
return PERMISSION_OPERATION_FAILURE;
}
final boolean hasGids = !ArrayUtils.isEmpty(permission.computeGids(userId));
final int[] oldGids = hasGids ? computeGids(userId) : NO_GIDS;
PermissionData permissionData = ensurePermissionData(permission);
得到权限信息后,将权限和userid存在一个 SparseArray数据结构中,用于查看对应权限是否申请
if (!permissionData.grant(userId)) {
return PERMISSION_OPERATION_FAILURE;
}
if (hasGids) {
final int[] newGids = computeGids(userId);
if (oldGids.length != newGids.length) {
return PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
}
}
return PERMISSION_OPERATION_SUCCESS;
}
private PermissionCallback mPermissionCallback = new PermissionCallback() {
@Override
public void onPermissionGranted(int uid, int userId) {
mOnPermissionChangeListeners.onPermissionsChanged(uid);
// 应用权限存储在data/system/user/0/runtime-permissions.xml 手机启动时由PackageManagerService读取
synchronized (mPackages) {
mSettings.writeRuntimePermissionsForUserLPr(userId, false);
}
}
... ...
}