14

我正在学习android开发,在java中阅读getExternalStorageDirectory时遇到了一些问题,我已经阅读了https://developer.android.com/reference/android/os/Environment但无法理解,有人可以帮我提供示例代码在爪哇。

4

3 回答 3

12

文档中您可以看到:

getExternalStoragePublicDirectory(String type)

此方法在 API 级别 29 中已弃用。为了提高用户隐私,不建议直接访问共享/外部存储设备。当应用程序以 Build.VERSION_CODES.Q 为目标时,从此方法返回的路径不再可供应用程序直接访问。通过迁移到Context#getExternalFilesDir(String)、MediaStore 或 Intent#ACTION_OPEN_DOCUMENT等替代方案,应用程序可以继续访问存储在共享/外部存储上的内容 。

不向此函数传递任何参数以将您的目录作为File对象:

context.getExternalFilesDir();

这里的“上下文”是一个对象,通过this.getContext();

this是Activity的当前对象。使用时请仔细检查范围。

重要的

访问内部存储,Manifest.permission.WRITE_EXTERNAL_STORAGE和/或Manifest.permission.READ_EXTERNAL_STORAGE文件AndroidManifest.xml中需要。

可选信息:

  1. 通常,内部存储在 Android 设备上具有路径 /sdcard/。这不是真正的路径,而是symlink

  2. 这令人困惑,但 Android 中的“外部 sdcard”实际上是指内部设备存储,而不是外部可弹出的设备外存储卡存储。另请注意,真正的外部 sdcard 不能完全访问

  3. Activity类扩展了Context类,这就是我们可以从中获取上下文的原因。

于 2019-06-29T18:17:30.817 回答
4

更新

从 Android 11 开始,它不允许在根目录中创建文件夹/文件,但我们仍然可以在公共目录的帮助下管理文件夹分离(它会显示一个已弃用的警告,但它会起作用)

fun getAbsolutePath(context: Context): File {
    return File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "{YOUR_FOLDER_NAME}"))
}

现在,使用公共目录路径创建文件

val file = File(getAbsolutePath(requireContext()), "FILENAME.EXTENSION")

年长者

使用此静态方法。目前我没有找到任何合法的方式来做到这一点。所以,我做了这个静态方法来获取 root 或 getAbsolutePath 文件路径。

public static File getAbsoluteDir(Context ctx, String optionalPath) {
        String rootPath;
        if (optionalPath != null && !optionalPath.equals("")) {
            rootPath = ctx.getExternalFilesDir(optionalPath).getAbsolutePath();
        } else {
            rootPath = ctx.getExternalFilesDir(null).getAbsolutePath();
        }
        // extraPortion is extra part of file path
        String extraPortion = "Android/data/" + BuildConfig.APPLICATION_ID
                + File.separator + "files" + File.separator;
        // Remove extraPortion
        rootPath = rootPath.replace(extraPortion, "");
        return new File(rootPath);
    }
于 2019-12-10T12:45:18.213 回答
1

使用getExternalFilesDir(), getExternalCacheDir(), or getExternalMediaDirs() (Context 上的方法) 代替Environment.getExternalStorageDirectory()

String root = mContext.getExternalFilesDir(null).getAbsolutePath();
File myDir = new File(root + "/" + mContext.getResources().getString(R.string.app_name) + "_share");
    myDir.mkdirs();

    
    
于 2020-08-29T06:10:26.147 回答