samedi 27 juin 2015

The correct way to create and write to an owned external SD card directory on Android 4.4 KitKat and up?

I have spent literally hours now looking for (and trying) many different ways to write some files to my 4.4 Android KitKat's external SD card. Now that Google has limited access to the filesystem on SD cards it seems you are forced to only be able to write to directories owned by the application (eg: /Android/data/com.mycompany.myapp/files/).

Finally I was able to get something working that creates a directory on the external SD card that can be written to. However I am curious why in order to create this owned directory on the external SD I first had to create a new file using a path to the internally owned directory?

first I create two globals to house the strings of both the internal and external paths.

MainActivity

public class MainActivity extends ActionBarActivity {
    String internalStorageDirectory;
    String externalStorageDirectory;

Then I ask the system where the directories are and start building absolute paths for both the internal and external variables followed by creating a new file for internalStorage.

onCreate()

internalStorageDirectory = this.getExternalFilesDir(null).toString();
File folderInt = new File(internalStorageDirectory); //THIS LINE IS CRUCIAL!!
Log.d("DEBUG", " - Internal Path" + internalStorageDirectory);// "/storage/emulated/0/Android/data/com.mycompany.httpreq2/files"


String ownedDirectory = "/Android/data/" + this.getPackageName();
externalStorageDirectory = System.getenv("SECONDARY_STORAGE").toString() + ownedDirectory + "/files//";
Log.d("DEBUG", " - External Path"+externalStorageDirectory);// "/storage/external/Android/data/com.mycompany.httpreq2/files//"

Finally I am able to save a file that I downloaded earlier from an AsyncTask.

doInBackground()

output = new FileOutputStream(externalStorageDirectory + "myawesomefile.mp4");

Then I was able to navigate to the SD card directory via adb shell and I could see my file.

adb shell output:

shell@QTAQZ3:/storage/external/Android/data/com.mycompany.myapp/files $ ls
ls
myawesomefile.mp4

So I guess my question is, why do I need to create a file for internal storage first:

File folderInt = new File(internalStorageDirectory); //THIS LINE IS CRUCIAL!!

before I can write to the external directory? Am I even doing this correctly?

Thanks for any insight into this, Cheers!

Aucun commentaire:

Enregistrer un commentaire