gpt4 book ai didi

java - 在 Android 上写入外部 SD 卡的通用方法

转载 作者:行者123 更新时间:2023-12-02 03:36:18 24 4
gpt4 key购买 nike

在我的应用程序中,我需要在设备存储中存储大量图像。此类文件往往用于设备存储,我希望允许用户能够选择外部 SD 卡作为目标文件夹。

我到处都读到 Android 不允许用户写入外部 SD 卡,SD 卡是指外部和可安装的 SD 卡和 不是外部存储 ,但文件管理器应用程序设法在所有 Android 版本上写入外部 SD .

在不同的 API 级别(Pre-KitKat、KitKat、Lollipop+)授予对外部 SD 卡的读/写访问权限的更好方法是什么?

更新 1

我尝试了 Doomknight 答案中的方法 1,但无济于事:
如您所见,在尝试写入 SD 之前,我正在运行时检查权限:

HashSet<String> extDirs = getStorageDirectories();
for(String dir: extDirs) {
Log.e("SD",dir);
File f = new File(new File(dir),"TEST.TXT");
try {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)==PackageManager.PERMISSION_GRANTED) {
f.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}

但是我收到访问错误,在两种不同的设备上尝试过:HTC10 和 Shield K1。
10-22 14:52:57.329 30280-30280/? E/SD: /mnt/media_rw/F38E-14F8
10-22 14:52:57.329 30280-30280/? W/System.err: java.io.IOException: open failed: EACCES (Permission denied)
10-22 14:52:57.329 30280-30280/? W/System.err: at java.io.File.createNewFile(File.java:939)
10-22 14:52:57.329 30280-30280/? W/System.err: at com.myapp.activities.TestActivity.onResume(TestActivity.java:167)
10-22 14:52:57.329 30280-30280/? W/System.err: at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1326)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.Activity.performResume(Activity.java:6338)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3336)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3384)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2574)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.ActivityThread.access$900(ActivityThread.java:150)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.os.Looper.loop(Looper.java:168)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5885)
10-22 14:52:57.330 30280-30280/? W/System.err: at java.lang.reflect.Method.invoke(Native Method)
10-22 14:52:57.330 30280-30280/? W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:819)
10-22 14:52:57.330 30280-30280/? W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:709)
10-22 14:52:57.330 30280-30280/? W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
10-22 14:52:57.330 30280-30280/? W/System.err: at libcore.io.Posix.open(Native Method)
10-22 14:52:57.330 30280-30280/? W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
10-22 14:52:57.330 30280-30280/? W/System.err: at java.io.File.createNewFile(File.java:932)
10-22 14:52:57.330 30280-30280/? W/System.err: ... 14 more

最佳答案

摘要
您可以将 grant read/write access 连接到 different api levels ( API23+ at run time ) 上的外部 SD 卡。
如果您使用特定于应用程序的目录,则 Since KitKat, 权限为 not necessary,否则为 required
通用方式:
history 表示没有通用的方法可以写入外部 SD 卡 but continues...
This factthese examples of external storage configurations for devices 证明。
基于 API 的方式:
KitKat 之前尝试使用 Doomsknight method 1, method 2 otherwise.
请求权限 in manifest (Api < 23) 和 at run time (Api >= 23)。
推荐方式:
当您不需要共享文件时,ContextCompat.getExternalFilesDirs 解决了 the access error
共享它的安全方式是使用 content providernew Storage Access Framework
隐私感知方式:
As of Android Q Beta 4 ,默认情况下,面向 Android 9(API 级别 28)或更低版本的应用没有看到任何变化。
默认情况下(或选择加入)以 Android Q 为目标的应用程序会在外部存储中分配 filtered view

  • 初始答案。

  • Universal way to write to external SD card on Android


    由于 universal way 没有 write to external SD card on Androidcontinuous changes :
  • Pre-KitKat:官方Android平台除异常(exception)情况外根本不支持SD卡。
  • KitKat:引入了 API,允许应用访问 SD 卡上应用特定目录中的文件。
  • Lollipop:添加 API 以允许应用请求访问其他提供商拥有的文件夹。
  • Nougat:提供了一个简化的 API 来访问常见的外部存储目录。
  • ... Android Q privacy change: App-scoped and media-scoped storage

  • What is the better way to grant read/write access to external SD cardon different API levels


    基于 Doomsknight's answermineDave SmithMark Murphy blog posts: 123 :
  • 理想情况下,使用 Storage AccessFramework

    DocumentFile
    Jared Rummler pointed 。或:
  • 使用 your app specific path /storage/extSdCard/Android/data/com.myapp.example/files
  • 为 pre-KitKat 添加 read/write permission to manifest,为该路径添加 no permission required later
  • 尝试使用您的 App 路径和 Doomsknight's methods 考虑 KitKat and Samsung case
  • 过滤并使用 getStorageDirectories 、您的应用程序路径和 KitKat 之前的读/写权限。
  • ContextCompat.getExternalFilesDirs 自 KitKat 以来。考虑到 devices that return internal first.
  • 更新了答案。

  • Update 1. I tried Method 1 from Doomknight's answer, with no avail:

    As you can see I'm checking for permissions at runtime beforeattempting to write on SD...


    我将使用您更新的问题的特定于应用程序的目录 to avoid the issue 和使用 getExternalFilesDir documentation 作为引用的 ContextCompat.getExternalFilesDirs()
    改进 heuristics 以根据 android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT 等不同 api 级别确定代表可移动媒体的内容

    ... But I get an access error, tried on two different devices: HTC10and Shield K1.


    请记住, Android 6.0 supports portable storage devices 和第三方应用程序必须通过 Storage Access Framework 。您的设备 HTC10Shield K1 可能是 API 23。
    您的日志显示 a permission denied exception 访问 /mnt/media_rw ,例如 API 19+ 的 this fix :
    <permission name="android.permission.WRITE_EXTERNAL_STORAGE" >
    <group gid="sdcard_r" />
    <group gid="sdcard_rw" />
    <group gid="media_rw" /> // this line is added via root in the link to fix it.
    </permission>
    我从未尝试过,所以我无法共享代码,但我会避免 for 尝试在所有返回的目录上写入并查找 the best available storage directory to write into based on remaining space
    也许 Gizm0's alternative 到您的 getStorageDirectories() 方法,这是一个很好的起点。
    如果您不需要 the issueContextCompat.getExternalFilesDirs 可以解决 access to other folders
  • Android 1.0 .. Pre-KitKat。

  • 在 KitKat 之前尝试使用 Doomsknight method 1 或通过 Gnathonic 读取 this response
    public static HashSet<String> getExternalMounts() {
    final HashSet<String> out = new HashSet<String>();
    String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
    String s = "";
    try {
    final Process process = new ProcessBuilder().command("mount")
    .redirectErrorStream(true).start();
    process.waitFor();
    final InputStream is = process.getInputStream();
    final byte[] buffer = new byte[1024];
    while (is.read(buffer) != -1) {
    s = s + new String(buffer);
    }
    is.close();
    } catch (final Exception e) {
    e.printStackTrace();
    }

    // parse output
    final String[] lines = s.split("\n");
    for (String line : lines) {
    if (!line.toLowerCase(Locale.US).contains("asec")) {
    if (line.matches(reg)) {
    String[] parts = line.split(" ");
    for (String part : parts) {
    if (part.startsWith("/"))
    if (!part.toLowerCase(Locale.US).contains("vold"))
    out.add(part);
    }
    }
    }
    }
    return out;
    }
    将下一个代码添加到您的 AndroidManifest.xml 并读取 Getting access to external storage

    Access to external storage is protected by various Androidpermissions.

    Starting in Android 1.0, write access is protected withthe WRITE_EXTERNAL_STORAGE permission.

    Starting in Android 4.1, readaccess is protected with the READ_EXTERNAL_STORAGE permission.

    In order to ... write files on the external storage, your app mustacquire ... systempermissions:

    <manifest ...>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    </manifest>

    If you need to both..., you need to requestonly the WRITE_EXTERNAL_STORAGE permission.


    读取 Mark Murphy's explanationrecommended Dianne HackbornDave Smith 帖子
    • Until Android 4.4, there was no official support for removable media in Android, Starting in KitKat, the concept of “primary” and “secondary” external storage emerges in the FMW API.
    • Prior apps are just relying on MediaStore indexing, ship with the hardware or examine mount points and apply some heuristics to determine what represents removable media.

  • Android 4.4 KitKat 引入了 the Storage Access Framework (SAF)

  • 由于错误而忽略下一个注释,但尝试使用 ContextCompat.getExternalFilesDirs() :
    • Since Android 4.2, there has been a request from Google for device manufacturers to lock down removable media for security (multi-user support) and new tests were added in 4.4.
    • Since KitKat getExternalFilesDirs() and other methods were added to return a usable path on all available storage volumes (The firstitem returned is the primary volume).

  • 下表说明了开发人员可能会尝试做什么以及 KitKat 将如何响应:
    enter image description here

  • Note: Beginning with Android 4.4, these permissions are not requiredif you're reading or writing only files that are private to your app.For more info..., see saving files thatare app-private.

    <manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="18" />
    </manifest>

    另请阅读 Paolo Rovelli's explanation 并尝试使用 Jeff Sharkey's solution,因为 KitKat:

    In KitKat there's now a public API for interacting withthese secondary shared storage devices.

    The new Context.getExternalFilesDirs() andContext.getExternalCacheDirs() methods can return multiple paths,including both primary and secondary devices.

    You can then iterateover them and check Environment.getStorageState() andFile.getFreeSpace() to determine the best place to store your files.

    These methods are also available on ContextCompat in the support-v4 library.


    Starting in Android 4.4, the owner, group and modes of files onexternal storage devices are now synthesized based on directorystructure. This enables apps to manage their package-specificdirectories on external storage without requiring they hold the broadWRITE_EXTERNAL_STORAGE permission. For example, the app with packagename com.example.foo can now freely accessAndroid/data/com.example.foo/ on external storage devices with nopermissions. These synthesized permissions are accomplished bywrapping raw storage devices in a FUSE daemon.


    使用 KitKat,您无需生根即可获得“完整解决方案”的机会是
    几乎为零:

    The Android project has definitely screwed up here.No apps get full access to external SD cards:

    • file managers: you cannot use them to manage your external SD card. Inmost areas, they can only read but not write.
    • media apps: you cannotretag/re-organize your media collection any longer, as those appscannot write to it.
    • office apps: pretty much the same

    The only place 3rd party apps are allowed to write on yourexternal card are "their own directories" (i.e./sdcard/Android/data/<package_name_of_the_app>).

    The only ways toreally fix that require either the manufacturer (some of them fixedit, e.g. Huawei with their Kitkat update for the P6) – or root... (Izzy's explanation continues here)


  • Android 5.0 引入了更改和 DocumentFile 帮助程序类。
  • getStorageState 在 API 19 中添加,在 API 21 中弃用,
    use getExternalStorageState(File)

    Here's a great tutorial for interacting with the Storage AccessFramework in KitKat.

    Interacting with the new APIs in Lollipop is very similar (Jeff Sharkey's explanation).


  • Android 6.0 Marshmallow 引入了新的 runtime permissions 模型。

  • Request permissions 在运行时如果 API 级别 23+ 并读取 Requesting Permissions at Run Time

    Beginning in Android 6.0 (API level 23), users grant permissions toapps while the app is running, not when they install the app ... or update the app ... user can revoke the permissions.

    // Assume thisActivity is the current activity
    int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
    Manifest.permission.WRITE_EXTERNAL_STORAGE);

    Android 6.0 introduces a new runtime permissions model where appsrequest capabilities when needed at runtime. Because the new modelincludes the READ/WRITE_EXTERNAL_STORAGE permissions, the platformneeds to dynamically grant storage access without killing orrestarting already-running apps. It does this by maintaining threedistinct views of all mounted storage devices:

    • /mnt/runtime/default is shown to apps with no special storagepermissions...
    • /mnt/runtime/read is shown to apps withREAD_EXTERNAL_STORAGE
    • /mnt/runtime/write is shown to apps withWRITE_EXTERNAL_STORAGE

  • Android 7.0 提供了一个简化的 API 来访问外部存储目录。

  • Scoped Directory AccessIn Android 7.0, apps can use new APIs to request access to specificexternal storage directories, including directories on removable mediasuch as SD cards...

    For more information, see the Scoped Directory Access training.


    阅读 Mark Murphy 的帖子: Be Careful with Scoped Directory AccessIt was deprecated in Android Q:

    Note that the scoped directory access added in 7.0 is deprecated inAndroid Q.

    Specifically, the createAccessIntent() method on StorageVolume isdeprecated.

    They added a createOpenDocumentTreeIntent() that can be used as analternative.


  • Android 8.0 Oreo .. Android Q Beta 更改。

  • Starting in AndroidO, theStorage Access Framework allows custom documentsprovidersto create seekable file descriptors for files residing in a remotedata source...

    Permissions,prior to Android O, if an app requested a permission at runtime and the permission was granted, the system also incorrectly grantedthe app the rest of the permissions that belonged to the samepermission group, and that were registered in the manifest.

    For apps targeting Android O, this behavior has been corrected. The app is granted only the permissions it has explicitly requested.However, once the user grants a permission to the app, all subsequentrequests for permissions in that permission group are automaticallygranted.

    For example, READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE...


    更新: 早期的 Android Q 测试版暂时用更细粒度的特定媒体权限替换了 READ_EXTERNAL_STORAGEWRITE_EXTERNAL_STORAGE 权限。
    注意: Google 在 Beta 1 中引入了 roles 并在 Beta 2 之前将它们从文档中删除...
    注意: 在早期 beta 版本中引入的特定于媒体 Collection 的权限 - READ_MEDIA_IMAGESREAD_MEDIA_AUDIOREAD_MEDIA_VIDEO - are now obsolete 更多信息:
    Mark Murphy 的 Q Beta 4(最终 API)评论: The Death of External Storage: The End of the Saga(?)

    "Death is more universal than life. Everyone dies, but not everyonelives." ― Andrew Sachs


  • 相关问题和推荐答案。

  • How can I get external SD card path for Android 4.0+?
    mkdir() works while inside internal flash storage, but not SD card?
    Diff between getExternalFilesDir and getExternalStorageDirectory()
    Why getExternalFilesDirs() doesn't work on some devices?
    How to use the new SD card access API presented for Android 5.0 (Lollipop)
    Writing to external SD card in Android 5.0 and above
    Android SD Card Write Permission using SAF (Storage Access Framework)
    SAFFAQ: The Storage Access Framework FAQ
  • 相关错误和问题。

  • Bug: On Android 6, when using getExternalFilesDirs, it won't let you create new files in its results
    Writing to directory returned by getExternalCacheDir() on Lollipop fails without write permission

    关于java - 在 Android 上写入外部 SD 卡的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068984/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com