gpt4 book ai didi

Android 开发 - 测试 SD 卡或假设它在那里?

转载 作者:搜寻专家 更新时间:2023-11-01 07:38:47 24 4
gpt4 key购买 nike

我的应用程序需要外部存储(SD 卡)才能保存用户数据。我到处搜索,但找不到任何最佳做法。

我...

  1. 只是假设存在外部存储并跳过添加检查和警报? (这里假设外部存储只会在极少数情况下丢失,因此不值得为此花费大量时间编写解决方案。典型用户永远不会移除他们的 SD 卡等)

    <
  2. 读取或写入外部存储时检查是否挂载? (用户可以随时移除他们的 SD 卡,但该应用程序仍然可以工作,直到需要访问他们的数据。)

  3. 在应用程序级别添加一个监听器以等待外部存储通知并在整个应用程序范围内显示模态警报? (这听起来很理想,但据我所知也可能有点矫枉过正。)

任何见解将不胜感激。

最佳答案

是的,你必须测试 sdcard 的存在,下面的函数会帮助你。

private boolean checkForDirectory()
{
boolean cardstate = true;

String state = Environment.getExternalStorageState();

if (Environment.MEDIA_BAD_REMOVAL.equals(state)) {
cardstate = false;
runDialog("Memory Card was removed before it was unmounted");
}
else if (Environment.MEDIA_CHECKING.equals(state)) {
runDialog("Memory Card is present and being disk-checked");
}
else if (Environment.MEDIA_MOUNTED.equals(state)) {
cardstate = true;
//runDialog("Memory Card is present and mounted with read/write access");
}
else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
runDialog("Memory Card is present and mounted with readonly access");
}
else if (Environment.MEDIA_NOFS.equals(state)) {
cardstate = false;
runDialog("Memory Card is present but is blank or using unsupported file system");
}
else if (Environment.MEDIA_REMOVED.equals(state)) {
cardstate = false;
runDialog("Memory Card is not present");
}
else if (Environment.MEDIA_SHARED.equals(state)) {
cardstate = false;
runDialog("Memory Card is present but shared via USB mass storage");
}
else if (Environment.MEDIA_UNMOUNTABLE.equals(state)) {
cardstate = false;
runDialog("Memory Card is present but cannot be mounted");
}
else if (Environment.MEDIA_UNMOUNTED.equals(state)) {
cardstate = false;
runDialog("Memory Card is present but not mounted");
}

File dir = new File(Environment.getExternalStorageDirectory() + "/gwc");
if(dir.exists() && dir.isDirectory())
{
System.out.println("Folder exists");
}
else
{
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + "/gwc");
myNewFolder.mkdir();
System.out.println("Folder gwc created ");
}
return cardstate;
}

关于Android 开发 - 测试 SD 卡或假设它在那里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6771089/

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