简体   繁体   中英

DocumentsContract.copyDocument() always fails

final String AUTHORITY = "com.android.externalstorage.documents";

Uri roottree  = DocumentsContract.buildTreeDocumentUri(AUTHORITY,"primary:");
Uri sourceuri = DocumentsContract.buildDocumentUriUsingTree(roottree,DocumentsContract.geTreeDocumentId(roottree) + "Folder1");
Uri TargetUri = DocumentsContract.buildDocumentUriUsingTree(roottree,DocumentsContract.getTreeDocumentId(roottree) + "Folder2");
Uri resulturi = DocumentsContract.copyDocument(myContentResolver,sourceuri,TargetUri);

Copying Folder1 into Folder2 always return null. CreateDocument, DeleteDocument even MoveDocument working without any issue.

I believe it was a deliberately bug. It didn't work and you need to rebuild the function. Here is simple sample:

public boolean copyFileUri(Uri FilePath, Uri ToFolder, String Name){boolean done=true;
    try {
        InputStream in = this.getContentResolver().openInputStream(FilePath);
        Uri uriOut=DocumentsContract.createDocument(getContentResolver(), ToFolder,  "text/plain", Name );
        OutputStream out = new FileOutputStream(getContentResolver().openFileDescriptor(uriOut, "w").getFileDescriptor());
        Uri uRename=DocumentsContract.renameDocument(getApplicationContext().getContentResolver(), uriOut, Name );
        if (uRename==null){/*RENAME WITH WHILE COUNTER*/}
        try { byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch(Exception e){done=false;}
        out.close(); in.close();
    } catch(Exception e){done=false;} return done;      
}

Note that you will need to DIY additional function for these case:

  • The destination folder have files with the same name, you need to add counter for rename or a switch to overwrite old file.
  • If you want to copy folder, it will a little more complex by add:
    • Detect Uri was folder or normal file
    • Create folder
    • Scan File
    • Recursion calling itself when scan so it scan whole the tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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