The path to the application's own external storage directory

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

context.getExternalFilesDir(null);

      

But using this method up to API level 19 requires permission WRITE_EXTERNAL_STORAGE

and I don't want to force the user to use this permission, especially my method only wants to return an abstract file and doesn't want to create a directory.

I can use this code:

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

      

But I think hardcoding is not safe. Is there a way to get this directory back without forcing the user to use the permission WRITE

?

+3


source to share


1 answer


If you want to avoid lowercase encoded string you can try to use it.



    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();
    }

      

0


source







All Articles