繁体   English   中英

如何在 API 29 中不推荐使用 getExternalStorageDirectory 时读取或写入文件?

[英]How to read or write file as getExternalStorageDirectory is deprecated in API 29?

I am learning android development and i am facing some problem to read getExternalStorageDirectory in java, I have read https://developer.android.com/reference/android/os/Environment but can't understand, can someone help me with example code在 java 中。

文档中您可以看到:

getExternalStoragePublicDirectory(String type)

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

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

context.getExternalFilesDir();

这里的“Context”是一个通过this.getContext();获取的对象this.getContext();

this是 Activity 的当前对象。 使用时请仔细检查示波器。

重要的

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

可选信息:

  1. 通常,内部存储在 Android 设备上的路径为 /sdcard/。 这不是一个真正的路径,而是一个符号链接

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

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

使用这个静态方法。 目前我没有找到任何合法的方法来做到这一点。 所以,我使用这个静态方法来获取 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);
    }

使用getExternalFilesDir()getExternalCacheDir()getExternalMediaDirs() (上下文方法)而不是Environment.getExternalStorageDirectory()

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

    
    

简短答案:

String path = getContext().getExternalFilesDir(null).getAbsolutePath();

2022年,不推荐使用Environment.getExternalStorageDirectoryEnvironment.getExternalStoragePublicDirectory
从 API 29 ~ 31 开始,它们已被标记为已弃用,但不在上面。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM