简体   繁体   中英

How to get a DocumentContract using Android Storage Access Framework

I am trying to implement the SAF in my app. I have managed to copy music files to the external sdcard using the following:

         Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    startActivityForResult(intent, REQUEST_CODE_OPEN_DIRECTORY);

which brings up the File/folder Picker

to copy:

   private String copyFile(String inputPath, String inputFile, Uri treeUri) {
    InputStream in = null;
    OutputStream out = null;
    String error = null;
    DocumentFile pickedDir = DocumentFile.fromTreeUri(getActivity(), treeUri);
    String extension = inputFile.substring(inputFile.lastIndexOf(".")+1,inputFile.length());

    try {
        DocumentFile newFile = pickedDir.createFile("audio/"+extension, inputFile);
        out = getActivity().getContentResolver().openOutputStream(newFile.getUri());
        in = new FileInputStream(inputPath + inputFile);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        // write the output file (You have now copied the file)
        out.flush();
        out.close();

    } catch (FileNotFoundException fnfe1) {
        error = fnfe1.getMessage();
    } catch (Exception e) {
        error = e.getMessage();
    }
    return error;
}

BUT when user selected "move" I want to delete the files in the original location(s) which may not be in the documenttree as they have nothing to do with what folder was picked. Their paths are taken from the Mediastore_DATA field. Question is how can I get a DocumentContract with those files so that I can delete them?

There is no way to obtain URI permission from SAF w/o invoking another UI.

Since you use MediaStore to obtain media file, you can use ContentResolver.delete() with the Media URI you have to delete it. I assume you have WRITE_EXTERNAL_STORAGE permission. I don't recommend using File to delete the underlying file directly as MediaStore won't have a chance to clean it up.

Alternatively, you can also try https://developer.android.com/reference/android/os/storage/StorageVolume.html#createAccessIntent(java.lang.String) to obtain tree URI permission to the entire primary storage. However it only works from API 24.

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