Android6.0之后对敏感权限进行了控制,即只有用户确认后才能够拥有权限,在AndroidManifest中声明还不够。
以下是在实际开发中写的关于权限确认的方法类。
package com.android.jierijt.tools;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class Permission {
private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 2;
static String[] permissions = new String[]{
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION
};
public static void checkPermissionGroup(Activity activity){
List<String> mPermissionList=new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
if (ContextCompat.checkSelfPermission(activity, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
mPermissionList.add(permissions[i]);
}
}
if (mPermissionList.isEmpty()) {//未授予的权限为空,表示都授予了
Toast.makeText(activity,"已经授权", Toast.LENGTH_LONG).show();
} else {//请求权限方法
String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
ActivityCompat.requestPermissions(activity, permissions, MY_PERMISSIONS_REQUEST_CALL_CAMERA);
}
}
public static void checkPermission(Activity activity,String tagPermission){
if (ContextCompat.checkSelfPermission(activity, tagPermission) != PackageManager.PERMISSION_GRANTED) {
//没有授予权限
ActivityCompat.requestPermissions(activity, new String[]{tagPermission}, MY_PERMISSIONS_REQUEST_CALL_CAMERA);
}
}
}