我从之前的帖子中仔细复制了以下代码片段,它在模拟器和我的 Nexus 9 设备上都有效,在一定程度上!
但是,我得到的只是一个空的“最近”文件夹,而且我从未到达写入文件的代码。
我必须更改什么才能获得正确的文档树?
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 意图中。打开 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”额外没有任何作用。用户应手动单击三点菜单上的“显示内部存储”。 SD 卡默认可见。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)