Android 开发:直接在三星设备上访问外部 SD 卡(使用 extSdCard 路径)?

Android Dev: Accessing external SD card directly on Samsung devices (with extSdCard path)?

我正在学习 Android 开发,因此对某些技术 Android 概念比较陌生,但我确实有很强的开发背景。

我正在编写一个应用程序,希望能够直接访问用户 SD 卡上的文件。测试设备是三星 Galaxy Tab 4。

三星似乎使用自定义方法安装 SD 卡,将其放置在 /storage/extSdCard 而不是更传统的 /sdcard

在我的应用程序中,我使用方法Environment.getExternalStoragePublicDirectory方法请求存储路径,并得到一个指向内部存储而不是SD卡的路径。 (/storage/sdcard0/...)

当我尝试直接访问 SD 卡存储 (/storage/extSdCard/...) 时,出现错误 open failed: EACCES (Permission denied)

此设备(可能还有任何用户的设备)的内部存储器可用存储空间非常有限。 (此设备内部只有 8GB 的​​存储空间,其中大部分都被应用程序占用了。)此外,我希望潜在的应用程序用户能够直接将文件放到他们的 MicroSD 卡上,而不必使用 Android用于将内容加载到应用程序的文件传输工具...

我可以通过三星设备上的应用程序 运行 直接访问外部 SD 卡吗?

测试代码:

public void doTest()
{
    FileWriter fw;

    File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "test.txt");
    Log.i("file","Trying to write a file at: "+f.getPath());
    try {
        fw = new FileWriter(f);
        fw.write("You got a file.");
        fw.flush();
        fw.close();
        Log.i("file", "Successfully wrote the file.");
    }
    catch (IOException e)
    {
        Log.i("file_error", "Could not write the file.");
        Log.i("file_error",e.getMessage());
    }

    f = new File("/storage/extSdCard/Documents", "test.txt");
    Log.i("file","Trying to write a file at: "+f.getPath());
    try {
        fw = new FileWriter(f);
        fw.write("You got a file.");
        fw.flush();
        fw.close();
        Log.i("file", "Successfully wrote the file.");
    }
    catch (IOException e)
    {
        Log.i("file_error", "Could not write the file.");
        Log.i("file_error",e.getMessage());
    }
}

I am writing an app that I want to be able to directly access files on the user's SD card.

这在 Android 4.4+ 上是不可能的,因为对 removable storage 的大部分直接访问都已被限制。例外情况包括预安装的应用程序和 运行 在已获得 root 权限的设备上并使用超级用户权限的应用程序。

Samsung appears to use a custom method of mounting the SD card, placing it at /storage/extSdCard rather than the more traditional /sdcard.

/sdcard 自 Android 2.x 以来在大多数设备上都未用于可移动媒体。

In my app, I used the method Environment.getExternalStoragePublicDirectory method to request the path for storage, and was given a path which points to the internal storage rather than the SD card. (/storage/sdcard0/...)

否,getExternalStoragePublicDirectory()指向外部存储。外部存储不是 removable storage内部存储完全是另一回事。

Any way I can access the external SD card directly from an app running on a Samsung device?

欢迎您在 Context 上使用 getExternalFilesDirs()getExternalCacheDirs()getExternalMediaDirs() 方法。注意复数方法名称。如果这些方法 return 2+ 个条目,则第二个和后续方法是可移动存储上的位置,您可以读取和写入,不需要权限。但是,您无法通过这种方式访问​​所有可移动存储,只能访问特定于您的应用程序的位置。

也欢迎您使用 the Storage Access Framework,允许用户选择内容的去向,包括将其放置在可移动存储上。但是,您不再使用文件和路径,而是使用内容和 Uri 值。

N Developer Preview 为 "Scoped Directory Access" 提供了另一种选择,它支持可移动存储。但是,目前(2016 年 3 月)这仍然是开发人员预览的一部分。