android - ACTION OPEN DOCUMENT TREE 只返回空的 Recent 文件夹

标签 android file-io

我从之前的帖子中仔细复制了以下代码 fragment ,它在模拟器和我的 Nexus 9 设备上都能正常工作,达到一定程度!

但是,我得到的只是一个空的 Recent 文件夹,而且我从未接触到写入文件的代码。

我必须更改什么才能获得正确的文档树?

   private void testDocumentTree() {

            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            startActivityForResult(intent, 42);
        }

        public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
            String TAG = "onActivityResult";
            if (resultCode == RESULT_OK) {
                Uri treeUri = resultData.getData();
                DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);

                // List all existing files inside picked directory
                for (DocumentFile file : pickedDir.listFiles()) {
                    Log.d(TAG, "Found file " + file.getName() + " with size " + file.length());
                }

                // Create a new file and write into it
                DocumentFile newFile = pickedDir.createFile("text/plain", "My Novel");
                try {
                    OutputStream out = getContentResolver().openOutputStream(newFile.getUri());
                    out.write("A long time ago...".getBytes());
                    out.close();
                } catch (FileNotFoundException e) {
                    Log.d(TAG, "File Not Found, reason: ", e);
                } catch (IOException e) {
                    Log.d(TAG,"IOException, reason: ", e);
                }
            }
        }

最佳答案

其他人提到了 DocumentsUI 上的选项,用户应该手动启用该选项。但是还有另一种选择。将这些额外内容添加到您的 ACTION_OPEN_DOCUMENT、ACTION_GET_CONTENT、ACTION_CREATE_DOCUMENT 或 ACTION_OPEN_DOCUMENT_TREE Intent 中。存储设置上的浏览按钮在打开 DocumentsUI 应用程序时使用这些额外功能。我认为第一个足以显示内部存储和 SD 卡。其他的都很好。

intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
intent.putExtra("android.content.extra.FANCY", true);
intent.putExtra("android.content.extra.SHOW_FILESIZE", true);

安卓10

我在 Android 10 模拟器和 OnePlus 7T 上试过,“SHOW_ADVANCED”extra 没有做任何事情。用户应手动单击三点菜单上的“显示内部存储”。默认情况下,SD 卡是可见的。

关于android - ACTION OPEN DOCUMENT TREE 只返回空的 Recent 文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27889377/

相关文章:

Android 通知操作按钮点击监听器

android - 如何在用户退出应用程序时保存 Android CheckBox 的状态?

Android异步任务: Only the original thread that created a view hierarchy can touch its views

c - 为什么我不能在 Ubuntu 中打开我的 txt 文件?

python - Python中文件操作的性能

ajax - 如何在不离开页面的情况下提供文件?

python - 使用 py2app 一旦 python 为 "compiled",open()/f.write() 就不起作用

java -> 无法隔离参数 com.android.build.gradle

java - 为什么 java.io.File 没有 close 方法?

Android 设备供应商系统签名 key 唯一性