以编程方式测试 Android 10+ 是否禁用旧版外部存储访问

Test programmatically if in Android 10+ the legacy external storage access is disabled

是否有一个简单的 API 调用可以告诉我 运行 在 Android 10 或更高版本上的应用程序是否必须使用范围存储访问,也就是说,如果正常文件访问, a.k.a。 "Legacy External Storage" 被禁用了?请注意,即使 AndroidManifest.xml 中的应用声明部分:

  android:requestLegacyExternalStorage="true"

未来由于Google政策变更,文件访问可能仍会被拒绝,所以测试这个值是没有用的。我找到的唯一方法是测试外部存储根目录是否可读,但为此,应用程序必须首先请求存储权限,如果旧存储被禁用,这对其他任何东西都没有用。

public static boolean mustUseScopedStorage() {
    // Impractical must first ask for useless Storage permission...
    File exSD = Environment.getExternalStorageDirectory();
    return !exSD.canRead(); // this test works only if Storage permission was granted.
}

我想我曾经看到一个新的 API 来检测这个,但是找不到那个文章了...

您可以使用android.os.Environment中的这两种方法:

  • isExternalStorageLegacy(File path)

    Returns whether the shared/external storage media at the given path is a legacy view that includes files not owned by the app.

  • isExternalStorageLegacy()

    Returns whether the primary shared/external storage media is a legacy view that includes files not owned by the app.

This value may be different from the value requested by requestLegacyExternalStorage in the app's manifest, since an app may inherit its legacy state based on when it was first installed.

Non-legacy apps can continue to discover and read media belonging to other apps via MediaStore.

如果您发现您可以访问遗留存储,我个人认为最好将数据迁移到分区存储并改为使用它,因为遗留存储可能会在没有警告的情况下停止工作。