runtime-permissions - 无法获得android 11中存储目录的运行时权限
问题描述
我的项目存储目录:/storage/emulated/0/Android/data/myprojectapp
问题:我要在运行时获取我的项目目录的存储访问权限
在 AndroidManifest.xml 中添加了下面提到的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
检查运行时权限的代码
@Override
public void onCreate(Bundle savedInstanceState){
Log.d(TAG, "onCreate() [IN]");
super.onCreate(savedInstanceState);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSION_READ_EXTERNAL_STORAGE_CONSTANT);
} else {
setMainActivity();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
@NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_READ_EXTERNAL_STORAGE_CONSTANT: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "permission granted"); // able to see this is the log as permission granted
setMainActivity();
} else {
Toast.makeText(this, "Need sdcard permissions", Toast.LENGTH_SHORT).show();
}
}
}
}
//After the permssion is granted in runtime below mentioned method is called
private void setMainActivity() {
static final String PKGPUSH_DIR = "/storage/emulated/0/Android/data/myprojectapp";
//checking whether the is writable or not
File directory = new File(Constants.PKGPUSH_DIR);
if(directory.canWrite()){
Log.i(TAG, "set as writable "+directory);
}else{
Log.i(TAG, "Set as not writable"); // always it return the log as set as not writable
}
}
首先,在授予运行时权限后没有创建目录有人能告诉我为什么即使在授予运行时权限之后也没有创建目录以及为什么它不能访问?
是因为 Android 11 范围存储更改:
defaultConfig { applicationId "myprojectapp" minSdkVersion 26 targetSdkVersion 30 }
解决方案
推荐阅读
- sql-server - MS SQL 从存储过程中获取字段列表而不执行
- java - 我应该使用继承吗?
- c# - 来自本地 WCF 服务的 HttpWebRequest
- sql - “分组”,然后排序
- html - 纯 CSS:悬停时文本上方的中心工具提示 pt。3
- python - 如果列表被就地修改,则 Traitlets 列表将不会运行回调
- python - Bokeh 未从 CheckboxGroup 更新绘图线更新
- javascript - 使用 JavaScript 将 HTML Canvas 拆分为行
- python - Python 中的 3D BPP 算法
- excel - excel从向下滚动冻结行和前3列