android6.0运行权限兼容方案:
方案1)targetSdkVersion<23修改build.gradle文件中的targetSdkVersion配置 设置在23以下
Android 6.0对于动态权限机制的开启主要根据应用设定的targetSdkVersion,具体来讲:
targetSdkVersion
是否默认禁用敏感权限
是否开启动态权限
<23
否
否
>=23
是
是
因此需要在项目配置文件中修改您的targetSdkVersion配置
方案2)targetSdkVersion>=23时,以READ_EXTERNAL_STORAGE为例
@SuppressLint("NewApi")
public void requestReadExternalPermission() {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "READ permission IS NOT granted...");
如果App的权限申请曾经被用户拒绝过,就需要在这里跟用户做出解释
if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
showLongToast("要求打开权限");
} else { //进行权限请求
Log.d(TAG, "进行权限请求");
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_REQUEST_CODE);
}
} else {
Log.d(TAG, "READ permission is granted...");
permissionGranted();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
Log.d(TAG, "requestCode=" + requestCode + "; --->" + permissions.toString()
+ "; grantResult=" + grantResults.toString());
switch (requestCode) {
case READ_EXTERNAL_STORAGE_REQUEST_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//申请成功,进行相应操作
// permission was granted
// request successfully, handle you transactions
permissionGranted();
} else {
//申请失败,可以继续向用户解释。
// permission denied
// request failed
Log.d(TAG, "用户拒绝了权限请求");
}
return;
}
default:
break;
}
}
//获取到权限
protected void permissionGranted() {
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResourceId());
requestReadExternalPermission();
}
备注:项目中权限很多的话,那就得需要封装下对权限的管理,我自己收藏了几个权限管理的开源框架,如下: