簡體   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