创建 Android 与所有版本和设备兼容的应用程序目录

Create Android application directory compatible with all versions and devices

我需要一个 Android 应用程序目录路径到我的应用程序图片兼容所有版本。我搜索了很多,但还没有找到与所有设备兼容的东西。现在我们有了这段代码,但它仍然在 picturesDir.exists()U55ZTE 设备上给出 NullPointerExcepction。

    File picturesDir;
    String state = Environment.getExternalStorageState();
    // Make sure it's available, if there is no SD card, create new directory objects to make
    // directory on device.
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        picturesDir = new File(Environment.getDataDirectory() + "/data/" + getApplicationContext().getPackageName() + "/Pictures/");
    } else if (Environment.getExternalStorageState() != null) {
        picturesDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    } else{
        String externalStoragePath = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        picturesDir = new File(externalStoragePath + getApplicationContext().getPackageName() + "/Pictures/");
    }

    if (!picturesDir.exists()) {
        picturesDir.mkdir();
    }

我们该怎么办?我不想检查它是否为空以避免崩溃。我想要一个可以保存图片的路径。谢谢。

根据 getExternalFilesDir 的文档:"the absolute path to application-specific directory. May return null if shared storage is not currently available"。因此根据文档,如果您使用 getExternalFilesDir.

,您 必须 检查空值

除了没有挂载之外,可能还有其他原因导致外部存储不可用。在调用 getExternalStorageState 和调用 getExternalFilesDir 之间也存在竞争的可能性。换句话说,SD 卡可能会在调用 getExternalStorageState() 报告它已安装后立即卸载,但在调用 getExternalFilesDir 之前。这种竞争条件可能会导致您的崩溃。