我正在尝试在棒棒糖设备上的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
翻译为Uri
哪个可以与DocumentFile
一起使用?
答案 0 :(得分:0)
您仍然可以使用File
对可移动外部存储设备具有读取权限。因此,您可以使用ACTION_OPEN_DOCUMENT_TREE
在DocumentFile
返回的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;