1、静态加权限:
在AndroidManifest.xml中静态加权限:
这是添加的是对android设备文件操作时的读写权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
2、动态添加权限:
在Activity中动态添加
注:在Android6.0之后添加权限时,静态和动态都有添加才可
//android 6.0 之后需要在activity中动态获取权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//申请WRITE_EXTERNAL_STORAGE权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
1);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//申请WRITE_EXTERNAL_STORAGE权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
}
动态添加权限之后,第一次运行程序会弹框提示是否用户同意。
3、动态添加多个权限:
//先定义一String数组存所有要添加的权限名称
//动态权限
private String[] permissions = new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.INTERNET,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.CHANGE_NETWORK_STATE,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.WRITE_SETTINGS,
};
//再定义ArrayList泛型集合来过滤实际要操作权限
private ArrayList<String> arrayList = new ArrayList();
//操作之前先清空arrayList
arrayList.clear();
//循环遍历
for (int a = 0 ;a < permissions.length; a++){
//先判断是否有对应权限
if (ContextCompat.checkSelfPermission(this, permissions[a])
!= PackageManager.PERMISSION_GRANTED) {
//没有就加进arrayList
arrayList.add(permissions[a]);
}
}
if (arrayList.isEmpty()){
return;
}else{
//申请权限requestPermissions第二个参数是String[],这里再把arrayList转换成string[]
ActivityCompat.requestPermissions(this, arrayList.toArray(new String[arrayList.size()]),
1);
}