即使具有给定的权限,也无法在外部存储上进行读/写 [英] Cannot READ/WRITE on External Storage, even having given Permissions
问题描述
在Huawei Mate 20上运行我的应用程序,以下行:
Running my App on a Huawei Mate 20, the following lines:
String ext_path = Environment.getExternalStorageDirectory().getAbsolutePath();
File ext_folder = new File(ext_path);
System.out.println("Path: " + ext_path + " Dir Check: " + ext_folder.isDirectory() + " Can read: " + ext_folder.canRead());
返回:路径:/storage/emulated/0目录检查:true可以读取:false"
Return: "Path: /storage/emulated/0 Dir Check: true Can read: false"
但是,我已经授予了所有权限,并且还将这些权限包括在清单中:
However, I have given all permissions and I have also included these in the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
不能Read()返回True吗?我无法写入或读取文件.可能是什么原因?
Shouldn't canRead() return True? I cannot write or read files. What could be the reason?
我也尝试过:
String extStore = System.getenv("EXTERNAL_STORAGE");
File f_exts = new File(extStore);
System.out.println(f_exts);
System.out.println(Arrays.toString(f_exts.listFiles()));
我得到:"EXTERNAL_STORAGE"和"null"
and I get: "EXTERNAL_STORAGE" and "null"
推荐答案
,您需要明确要求用户授予所述权限.否则它将无法在较新的android vesions中工作.尝试在onCreate中添加此内容
you need to explicitly ask the user to grant said permissions. else it wont work in newer android vesions.try adding this in onCreate
ActivityCompat.requestPermissions(MainActivity.this, new String[]{READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE},111);
还有
如果您要定位Android Q,那么Environment.getExternalStorageDirectory()不再导致可访问的文件夹,我认为这实际上是您的问题.不推荐使用它,而推荐使用Context.getExternalFilesDir(null)来返回文件.值得一试,因为您的应用程序外部存储应该类似于"/storage/emulated/0/Android/data/com.example.android.YourApp/",并且在该位置您应该具有读写访问权限
If you are TARGETING Android Q also Environment.getExternalStorageDirectory() no longer leading to an accessible folder, which i think is actually your problem. it is deprecated in favor of Context.getExternalFilesDir(null) which returns a file. that is worth a try as your apps external storage should be something like "/storage/emulated/0/Android/data/com.example.android.YourApp/" and on that one you should have read and write access
这篇关于即使具有给定的权限,也无法在外部存储上进行读/写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!