Android 6.0以上的权限申请的问题

 一直都有权限申请的问题,没有足够的重视,最近总是受到困扰,算了不说了,看代码吧!

1、先判断sdk的版本号
if (Build.VERSION.SDK_INT >= 23) {
checkAndRequestPermission();//检查权限
} else {
// 如果是Android6.0以下的机器,默认在安装时获得了所有权限,可以直接调用SDK
}


2、@TargetApi(Build.VERSION_CODES.M)
private void checkAndRequestPermission() {
List lackedPermission = new ArrayList();
if (!(checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED)) {
lackedPermission.add(Manifest.permission.READ_PHONE_STATE);
}

if (!(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
  lackedPermission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}

if (!(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
  lackedPermission.add(Manifest.permission.ACCESS_FINE_LOCATION);
}

// 权限都已经有了,那么直接调用SDK
if (lackedPermission.size() == 0) {
  //处理自己的事
} else {
  // 请求所缺少的权限,在onRequestPermissionsResult中再看是否获得权限,如果获得权限就可以调用SDK,否则不要调用SDK。
  String[] requestPermissions = new String[lackedPermission.size()];
  lackedPermission.toArray(requestPermissions);
  requestPermissions(requestPermissions, 1024);
}

}

private boolean hasAllPermissionsGranted(int[] grantResults) {
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
return false;
}
}
return true;
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1024 && hasAllPermissionsGranted(grantResults)) {
fetchSplashAD(this, container, skipView, Constants.APPID, Constants.SplashPosID, this, 0);
} else {
// 如果用户没有授权,那么应该说明意图,引导用户去设置里面授权。
Toast.makeText(this, “应用缺少必要的权限!请点击\”权限\”,打开所需要的权限。”, Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse(“package:” + getPackageName()));
startActivity(intent);
finish();
}
}

你可能感兴趣的:(android,Android,PHP)