【发布时间】:2023-01-06 22:55:28
【问题描述】:
第一步,系统会提示我在外部 SD 卡上选择一个文件夹。我这样做并选择一个文件夹。
public void GetPermission(){
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
startActivityForResult(intent, 42);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (resultCode != RESULT_OK)
return;
Uri treeUri = resultData.getData();
getContext().getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
稍后我将一个 zip 文件(通过 asynctask)下载到从 Internet 上选择的文件夹中。只是为了测试我通过以下例程成功地将文件下载到选择的文件夹
uri_ext = Uri.parse(uri_string);
URLConnection conexion = url_download.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url_download.openStream());
OutputStream output = null;
DocumentFile pickedDir = DocumentFile.fromTreeUri(the_context, uri_ext);
DocumentFile newFile = pickedDir.createFile("application/zip", zipname);
output = the_context.getContentResolver().openOutputStream(newFile.getUri());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
if (isCancelled()) break;
}
output.flush();
output.close();
input.close();
之后,该文件存在于所选文件夹中。 下载不应发生在所选文件夹中,而应发生在所选文件夹的子文件夹中。 所以我用下面的代码创建了一个子文件夹:
DocumentFile new_Dir = DocumentFile.fromTreeUri(context, uri_ext);
new_Dir.createDirectory("new_subfolder");
uri_string = uri_string + "%2Fnew_subfolder");
// uri_string = uri_string + "/new_subfolder"); also checked
// no other code, nothing else
之后子文件夹存在。 现在,我尝试使用与上面完全相同的代码(除了来自 varibale uri_string 的 uri 路径)将 zip 文件从互联网加载到新的子文件夹中。 结果:无法下载到新的子文件夹。
为什么? 我究竟做错了什么? 我必须改变什么?
【问题讨论】:
-
“但我无法写入新的子文件夹,除非我再次请求它们的许可并明确选择它们”——您可能想扩展您的minimal reproducible example 以展示您是如何尝试这样做的。
-
can write files using an outputstream to the selected folder不,那是不可能的。您无法打开文件夹的输出流。只为一个文件。 -
to which you've given permissions你不能给权限。您可以获得所选文件夹的权限,并根据需要将其永久化。 -
您已授予权限:这就是我的意思。我获得了对所选文件夹的权限,但没有对新子文件夹的权限
-
可以使用输出流将文件写入所选文件夹:我可以使用输出流将文件写入所选文件夹,并且可以如上所述创建 ab 子文件夹。但是我不能在新的子文件夹中写输出流。这就是我想要的(没有新的权限对话框)。我必须做什么。
标签: android android-external-storage removable-storage