我已經仔細複製了以前的文章中的以下代碼片段,它在模擬器和我的Nexus 9設備上都能正常工作!操作OPEN DOCUMENT TREE只返回空文件夾最近的文件夾
但是,我得到的只是一個空的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);
}
}
}
FWIW,我在這裏補充一個問題:https://code.google.com/p/android/issues/detail?id=202116 –