今天在开发一个apk时:
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE,
Manifest.permission.ACCESS_COARSE_LOCATION},PER_REQUEST_CODE);
需要动态获取运行时权限,此时涉及到这样一个方法:
public final void requestPermissions(@NonNull String[] permissions, int requestCode)
进入到该方法中:
public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
if (requestCode < 0) {
throw new IllegalArgumentException("requestCode should be >= 0");
}
if (mHasCurrentPermissionsRequest) {
Log.w(TAG, "Can request only one set of permissions at a time");
// Dispatch the callback with empty arrays which means a cancellation.
onRequestPermissionsResult(requestCode, new String[0], new int[0]);
return;
}
Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
mHasCurrentPermissionsRequest = true;
}
从该方法体可以看到,共请求两个参数,前者为一个申请权限的String数组,后者参数为int类型参数。
注意,源码中这样解释到
译:请求授予此应用程序的权限。这些权限*必须在您的清单中请求,不应将它们授予您的应用,并且应具有保护级别
即需要在清单文件中请求:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
大功告成。