【问题标题】:Create Android application directory compatible with all versions and devices创建兼容所有版本和设备的Android应用程序目录
【发布时间】:2017-08-07 09:22:00
【问题描述】:

我需要一个与所有版本兼容的应用程序图片的 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();
    }

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

【问题讨论】:

  • “它仍然给出 NullPointerExcepction”——请编辑您的问题并发布与此异常相关的完整 Java 堆栈跟踪。我相信你的算法和设备一样是你的困难的根源,堆栈跟踪将帮助我确认你的症状。
  • 即使您在检查 SD 卡状态时以某种方式避免了错误,也有可能随时提取 SD 卡或发生 IO 错误。所以无论如何你都必须捕获 IO 错误。不要不惜一切代价让代码变得漂亮,你做不到。
  • 刚刚编辑过 CommonsWare!

标签: android directory android-external-storage android-storage


【解决方案1】:

根据 getExternalFilesDir 的文档:“应用程序特定目录的绝对路径。如果共享存储当前不可用,则可能返回 null”。因此,根据文档,如果您使用 getExternalFilesDir,您必须检查 null。

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

【讨论】:

  • 谢谢!我会检查一下,如果一些用户仍然给出这个错误,我会回到这里。谢谢。
猜你喜欢
  • 2012-09-06
  • 1970-01-01
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多