[英]Lollipop and sd-card
我正在嘗試在棒棒糖設備上的SD卡上創建一個文件。 我知道ACTION_OPEN_DOCUMENT_TREE,以及如何獲得SD卡的root權限。
我想要實現的是:
ACTION_OPEN_DOCUMENT_TREE
,然后在onActivityResult
使用findFile
在正確的位置創建文件: ACTION_OPEN_DOCUMENT_TREE
碼:
public void test()
{
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, 1);
}
public void onActivityResult(int requestCode, int resultCode, Intent resultData)
{
if (resultCode == RESULT_OK)
{
Uri treeUri = resultData.getData();
final int takeFlags = resultData.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION;
getContentResolver().takePersistableUriPermission(treeUri, takeFlags);
//assuming he picked "/storage/emulated/0/a/b/c/d"
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
DocumentFile a = pickedDir.findFile("a");
DocumentFile b = a.findFile("b");
DocumentFile c = b.findFile("c");
DocumentFile d = c.findFile("d");
DocumentFile newFile = d.createFile("text/plain", "somefile.txt");
OutputStream out;
try
{
out = getContentResolver().openOutputStream(newFile.getUri());
out.write("A long time ago...".getBytes());
out.close();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
問題是如何在onActivityResult
知道用戶實際選擇了sdcard的根? 他本可以選擇/storage/emulated/0/a1/a2
,如果該文件夾有子文件夾a/b/c/d
,我會在錯誤的文件夾中創建文件(因為findFile("a");findFile("b"); etc..
也會成功)。
此外,下次用戶選擇一個文件夾(使用我自己的文件夾選擇器)時,我會獲得path
,而不是Uri
,如何將該path
轉換為可與DocumentFile
一起使用的Uri
?
您仍然可以使用File
對可移動外部存儲進行讀取訪問。 因此,您可以使用DocumentFile
從ACTION_OPEN_DOCUMENT_TREE
返回的Uri目錄中創建一個具有唯一名稱的臨時文件。 和Uri
然后檢查它是否應該使用File
和路徑。 如果myPath
與treeUri
匹配,則以下代碼返回true。
String myPath = "/storage/sdcard1/Podcasts";
Uri treeUri = resultIntent.getData();
int i = 0;
File f;
String s;
while ((f = new File(myPath + (s = "/tmp" + i + ".mp3"))).exists()) ++i;
final DocumentFile d = treeDir.createFile("audio/mp3", s);
if (d == null) return false;
try {
OutputStream str = getContentResolver().openOutputStream(d.getUri());
str.write(new byte[10]);
str.close();
} catch (IOException e) {
return false;
}
final boolean fExists = f.exists();
d.delete();
return fExists;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.