简体   繁体   English

外部存储中App自己的目录的路径

[英]Path to App own directory in External Storage

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: 在库中,我想返回一个表示外部存储中App自己的目录的文件,该方法返回的目录:

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. 但是在API级别19之前使用此方法,需要WRITE_EXTERNAL_STORAGE权限,我不想强​​制用户使用此权限,特别是我的方法只想返回抽象文件而不想创建目录。

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? 但我认为硬编码不安全。有没有办法在不强制用户使用WRITE权限的情况下返回该目录?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 应用程序在本机代码中进行外部存储的路径 - App's path for external storage in native code Flutter:在外部存储路径上创建目录 - 路径提供程序 getExternalStorageDirectory() - Flutter : Create directory on external storage path - path provider getExternalStorageDirectory() 在平板电脑的Android应用程序中获取外部存储路径 - Get external storage path in android app for tablet 如何在android中创建外部存储目录,将外部存储路径显示为“storage / emulated / 0”? - How to create directory in external storage in android which show external storage path as “storage/emulated/0”? android ::如何在外部存储中的app数据目录上设置app图标, - android:: how to set app icon on app data directory in external storage , 在外部存储中创建目录 - Creating directory in External storage 通往外部存储的安全途径 - A Safe Path to External Storage 如何打开我的应用程序的外部/共享存储目录 - How to open my app's external/shared storage directory Android 11 - 在外部存储上创建应用程序特定目录 - Android 11 - Creating app-specific directory on external storage Android 11 不会在外部存储上创建应用程序目录 - Android 11 doesn't create app directory on external storage
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM