问题
I am working on an Android tablet application that is being used by law enforcement. I had the tablet backup all the data to an external SD card. I wanted to be able to recover data from the card in case the tablet got destroyed while the police officers were fighting crime. I used this code to store the backup:
File file = new File("/mnt/extSdCard/" + NewOrLoad.directoryName + "settings.dat");
try {
bW = new BufferedWriter(new FileWriter(file));
Gson gson = new Gson();
String json = gson.toJson(dreform);
bW.write(json);
bW.close();
} catch (IOException e) {
e.printStackTrace();
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
It worked fine. Unfortunately the newest batch of tablets purchased are running KitKat and this code doesn't work anymore. The only solutions I found involve rooting the tablets, which is just not feasible in my case. Is there a workaround?
回答1:
It worked fine
Only for devices where /mnt/extSdCard
existed and was writeable. This is outside the bounds of the Android SDK, and there is no guarantee that any device will honor that specific path. Perhaps you were in a controlled environment, with a single device model, where making this assumption was (relatively) safe.
Is there a workaround?
As 323go mentions in the comments, you are welcome to use getExternalFilesDirs() (note the plural). If there is more than one element in the resulting list, the second and subsequent entries will be for "secondary external storage" such as removable cards. You can read and write from this directory without any required permissions.
There is also ContextCompat, which offers a getExternalFilesDirs()
implementation that works all the way back to API Level 4. It will only ever return one value on devices running less than API Level 19, but it allows you to skip version checking yourself, as plenty of API Level 19+ devices will also only return one value (e.g., they do not have an SD card slot populated with a card).
I recently wrote a series of blog posts attempting to clarify the storage situation. You may be particularly interested in the one on removable storage.
来源:https://stackoverflow.com/questions/23429544/saving-to-sd-card-in-kitkat