'How to write files on SD Card from Android API 24+

I have a big problem. I want to save some files that I download from internet with my application, into my SD card fallowing this path:

/storage/9016-4EF8/Android/data/com.my.application/files

But I don't want to hardcode this string inside my code. So how can I do it programmatically? I have already ask permission to write on external storage.

Currently inside my code there is this piece of code below:

File sdcard = new File(context.getExternalFilesDir(null).getAbsolutePath() + "/Video scaricati/");

But with it, my application saves the files inside:

/storage/emulated/0/Android/data/com.my.application/files/Video scaricati

that it isn't in my SD card.

How can I do it?



Solution 1:[1]

Take the second item returned by

File dirs[] =getExternalFilesDirs();

Check if the array contains more then one element before use. Not everybody puts a micro SD card in.

Solution 2:[2]

Try changing to Environment.getExternalStorageDirectory() like this

new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video scaricati/");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 blackapps
Solution 2 Bach Vu