前言
Android 6.0 后,非系统应用权限获取收紧,应用需要动态的申请权限。
你除了AndroidManifest.xml中定义需要的权限,还需要在Java代码中再需要对应权限前提示用户授权。
正文
第一步
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
第二步
定义需要授权的权限
//申请需要的所有权限 private final String REQUEST_MANIFEST_PERMISSION[] = new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE };
PS:REQUEST_MANIFEST_PERMISSION中定义的需要跟AndroidManifest.xml配对,要不然无法申请到权限。
申请权限授权
public void requestPerssion(Activity activity, int permission_request_code) { if (null == activity) { Log.d(TAG, "requestPerssion null : "); return; } // Android 6.0后非系统应用需要申请权限 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { ActivityCompat.requestPermissions(activity, REQUEST_MANIFEST_PERMISSION, permission_request_code); } return; }
重写权限状态的回调
/** * @param requestCode 请求时的request code * @param permissions 返回的权限的数组 * @param grantResults 返回对应权限申请状态的数组[-1 申请失败,0申请成功] */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case PERMISSION_REQUEST_CODE: if (grantResults != null && permissions != null) { for (int i = 0; i < grantResults.length; i++) { Log.d(TAG, "grantResults[" + i + "]:" + grantResults[i]); Log.d(TAG, "permissions[" + i + "]:" + permissions[i]); } } break; } }
权限申请成功状态
/** * Permission check result: this is returned by {@link #checkPermission} * if the permission has been granted to the given package. */ public static final int PERMISSION_GRANTED = 0; /** * Permission check result: this is returned by {@link #checkPermission} * if the permission has not been granted to the given package. */ public static final int PERMISSION_DENIED = -1;
参考文章
© 版权声明