声明权限:
首先在清单文件中写出相应权限
<!--存储权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
获取权限:
1、 声明变量记录是否获得权限
int REQUEST = 0;
2、判断是否有相应权限,如果没有则获取
//判断是否已经获取相应权限 对应权限
if (ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
String str = etName.getText().toString().trim();
saveText(str);
}
// 若没有获得相应权限,则弹出对话框获取
else { //记录是否获得权限
ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST);
}
3、重写 onRequestPermissionsResult 获取是否得到授权
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == this.REQUEST) {
// 如果用户赋予全选,则执行相应逻辑
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
String str = etName.getText().toString().trim();
saveText(str);
} else {
toast("拒绝授权");
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}