I am making an android app which lets the user transfer some files from internal storage to external storage(SD card) using SAF.
This is how I call an intent to let the user choose the SD card directory.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, 42);
And this is my onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent data) {
treeUri = data.getData();
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getActivity().getContentResolver().takePersistableUriPermission(treeUri, takeFlags);
}
I am taking permission for whole SD card so that i can move or delete any file in sd card any time .The problem is that even after taking permission i am not able to move or delete any file in SD card.
How should i move a file from internal Storage to external(SD card) for android 5.0 and above.
EDIT:This is the code i am using to move files.
public static void MoveFiles(File src, File dst) throws IOException
{
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try
{
inChannel.transferTo(0, inChannel.size(), outChannel);
}
finally
{
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
src.delete();
}
}
This is how I finally solved the issue.
First call an intent to let the user grant write permission for whole SD card.
Then on onActivityResult take write permission.
And this is the code I used to copy files to SD card.
The above code uses the following two methods.
getDocumentFileIfAllowedToWrite method which returns DocumentFile if allowed to write.
And mime method which returns the mime type of the file.
I have tested the above code with Android Lollipop and Marshmallow.
EDIT: This is the link to the FileUtils class.