Path to App own directory in External Storage

127 views Asked by At

In a library, I want to return a file that represents App own directory in External Storage, the directory that is returned by this method:

context.getExternalFilesDir(null);

But using this method before API Level 19, needs WRITE_EXTERNAL_STORAGE permission and I do not want to force user to use this permission, specially my method only want to return abstract File and does not want to create directory.

I can use this code:

Environment.getExternalStorageDirectory().getCanonicalPath() + "/Android/data/" + packageName + "/files";

But I think hard coding is not safe.Is there a way to return that directory without forcing user to use WRITE permission?

1

There are 1 answers

3
alijandro On

If you want to avoid the hard coded string, you could try to use reflect.

    Class<?> environmentClass = Environment.class;
    try {
        Field androidDirectoryField = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            androidDirectoryField = environmentClass.getDeclaredField("DIR_ANDROID");
        } else {
            androidDirectoryField = environmentClass.getDeclaredField("DIRECTORY_ANDROID");
        }
        androidDirectoryField.setAccessible(true);
        final String externalDir = Environment.getExternalStorageDirectory().getAbsolutePath() 
                + getFilesDir().getAbsolutePath().replaceFirst("data", androidDirectoryField.get(null).toString());

        Log.d(TAG, "external directory " + externalDir);
    } catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }