6.0权限很烦人,为了更好的用户体验,还是需要动态的添加运行时权限。
对于android6.0以上运行时权限,清单文件里面注册已经没作用,因此我们需要动态申请。
话不多说,直接上代码,希望对各位开发者能有一定的帮助。
public class PermissionsChecker {private final Context mContext; public PermissionsChecker(Context context) {mContext = context.getApplicationContext(); }// 判断权限集合 public boolean lacksPermissions(String... permissions) {for (String permission : permissions) {if (lacksPermission(permission)) {return true; }}return false; }// 判断是否缺少权限 private boolean lacksPermission(String permission) {return ContextCompat.checkSelfPermission(mContext, permission) == PackageManager.PERMISSION_DENIED; }// 含有全部的权限 public boolean hasAllPermissionsGranted(@NonNull int[] grantResults) {for (int grantResult : grantResults) {if (grantResult == PackageManager.PERMISSION_DENIED) {return false; }}return true; }// 显示缺失权限提示 public void showMissingPermissionDialog(final Activity mContext) {AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle(R.string.help); builder.setMessage(R.string.string_help_text); builder.setCancelable(false); // 拒绝, 退出应用 builder.setNegativeButton(R.string.quit, new DialogInterface.OnClickListener() {@Override public void onClick(DialogInterface dialog, int which) {dialog.dismiss(); mContext.finish(); }}); builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {@Override public void onClick(DialogInterface dialog, int which) {
//跳转到设置界面
然后在需要权限的地方,动态申请权限,一般在onCreate里面进行判断。Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:"+ mContext.getPackageName()));mContext.startActivity(intent);} }); builder.show(); }}
例如,需要申请的权限,可一次多个申请
private static final String[] PERMISSIONS = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; private PermissionsChecker mPermissionsChecker; // 权限检测器 private boolean isRequireCheck = true; // 是否需要系统权限检测
private static final int PERMISSION_REQUEST_CODE = 11; // 系统权限管理页面的参数 private void getSdDPermission() {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {mPermissionsChecker = new PermissionsChecker(this); if (isRequireCheck) {// 缺少权限时, 进入权限配置页面 if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_REQUEST_CODE);// 请求权限 } else { // 全部权限都已获取 }} else {isRequireCheck = true; }}else {//如果版本低于23,正常情况 } }
//请求的回调
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {if (requestCode == PERMISSION_REQUEST_CODE && mPermissionsChecker.hasAllPermissionsGranted(grantResults)) {isRequireCheck = true; //权限已经获取,正常情况 } else {isRequireCheck = false;
//显示权限缺失的dialog mPermissionsChecker.showMissingPermissionDialog(SplashActivity.this); } }