一、多权限申请
①在oncreat()方法中写此方法
/**
* 6.0之后的动态申请权限
*/
checkRequiredPermission(LoginActivity.this);
②
/**
* 检查权限
* @param activity
*/
private void checkRequiredPermission(final Activity activity) {
for (String permission : permissionsArray) {
if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
}
}
if (permissionsList.size()!=0){
ActivityCompat.requestPermissions(activity, permissionsList.toArray(new String[permissionsList.size()]), REQUEST_CODE_ASK_PERMISSIONS);
}
}
③实现回调
//动态申请权限的返回值
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(LoginActivity.this, "权限开启" + permissions[i], Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, "权限禁止" + permissions[i], Toast.LENGTH_SHORT).show();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
二、单权限申请(也可以直接用多权限申请的方法,在里面只写一个权限):
①
第一步判断时候授权。
if (Build.VERSION.SDK_INT >= 23) {
int checkCallPhonePermission = ContextCompat.checkSelfPermission(FoodActivity.this, Manifest.permission.CAMERA);
if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(FoodActivity.this,new String[]{Manifest.permission.CAMERA},222);
return;
}else{
openCamra();//调用具体方法
}
} else {
openCamra();//调用具体方法
}
②写回调
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
//就像onActivityResult一样这个地方就是判断你是从哪来的。
case 222:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
openCamra();
} else {
// Permission Denied
Toast.makeText(FoodActivity.this, "很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。", Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}