android 权限申请代码
单个权限的申请
private void requestVoicePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
Log.d("geaosu", "用户看到解释后, 再次请求权限 - 录音");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 0);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 0);
Log.d("geaosu", "请求权限 - 录音");
}
} else {
Log.d("geaosu", "有权限 - 录音");
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permission, int[] grantResults) {
switch (requestCode) {
case 0:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("geaosu", "同意权限");
} else {
Log.d("geaosu", "拒绝权限");
}
break;
}
}
多个权限的申请
private String[] permissionList = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.LOCATION_HARDWARE,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.WRITE_SETTINGS,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
};
private String[] permissionList2 = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
private void requestPermissions() {
try {
if (Build.VERSION.SDK_INT >= 23) {
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, permissionList, 1);
}
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, permissionList2, 1);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
这里也是一种申请方式
private void checkPermissions() {
List<String> permissions = new LinkedList<>();
addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE);
addPermission(permissions, Manifest.permission.RECORD_AUDIO);
addPermission(permissions, Manifest.permission.INTERNET);
addPermission(permissions, Manifest.permission.READ_PHONE_STATE);
if (!permissions.isEmpty()) {
ActivityCompat.requestPermissions(this, permissions.toArray(new String[permissions.size()]), MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
}
private void addPermission(List<String> permissionList, String permission) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(permission);
}
}