繁体   English   中英

棒棒糖和SD卡

[英]Lollipop and sd-card

我正在尝试在棒棒糖设备上的SD卡上创建一个文件。 我知道ACTION_OPEN_DOCUMENT_TREE,以及如何获得SD卡的root权限。

我想要实现的是:

  • 在我自己的文件夹浏览器中,用户选择要在其中创建文件的文件夹(在SD卡上)(例如“/ storage / emulated / 0 / a / b / c / d”)
  • 第一次发生这种情况时,我使用ACTION_OPEN_DOCUMENT_TREE ,然后在onActivityResult使用findFile在正确的位置创建文件:
  • 下次用户在SD卡上选择一个文件夹时,他不需要使用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对可移动外部存储进行读取访问。 因此,您可以使用DocumentFileACTION_OPEN_DOCUMENT_TREE返回的Uri目录中创建一个具有唯一名称的临时文件。 Uri 然后检查它是否应该使用File和路径。 如果myPathtreeUri匹配,则以下代码返回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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM