格式化SD卡的Android
观光应该是简单的,但由于大部分的时间,在机器人,则不是。我需要的,如果用户选择在我的应用程序的选项格式化SD卡。不要问我为什么要这么做,如果是已经在操作系统...不实际的,但它是我需要实现的必要条件。正如你可能知道,有在设置\存储\删除SD卡选项。我接过一看Froyo的源头code,它是这样的:
Things should be simple, but as most of the time, in Android, aren't. I need to format the SD card if the user selects the option in my app. Don't ask me why I need to do this if it's already in the OS... not practical but it's a requirement that I need to implement. As you may know, there is an option in Settings \ Storage \ Erase SD Card. I took a look at the froyo source code and it's something like:
final IMountService service =
IMountService.Stub.asInterface(ServiceManager.getService("mount"));
if (service != null) {
new Thread() {
public void run() {
try {
service.formatVolume(Environment.getExternalStorageDirectory().toString());
} catch (Exception e) {
// Intentionally blank - there's nothing we can do here
Log.w("MediaFormat", "Unable to invoke IMountService.formatMedia()");
}
}
}.start();
} else {
Log.w("MediaFormat", "Unable to locate IMountService");
}
它使用 android.os.storage.IMountService
和 android.os.ServiceManager
,我似乎没有到有权访问它。所以,当我看到它,我可以递归搜索所有文件并将其删除,但是,这将是不是我的口味......我也可以开始从删除SD卡的屏幕给用户。
It uses android.os.storage.IMountService
and android.os.ServiceManager
and I don't seem to have access to it. So, as I see it I could recursively search every file and delete it but that would be "not on my taste"... or I could start the screen from Erase SD card to the user.
任何帮助更多的则是值得欢迎的,因为我卡住了。
Any help is more then welcome, as I am stuck.
我无法再次找到这里的问题上如此,但它有一个有效的解决方案。因此,所有归功于那家伙;)
I can't find again the question here on SO, but It had a working solution. So all credit goes to that guy ;)
public void wipeMemoryCard() {
File deleteMatchingFile = new File(Environment
.getExternalStorageDirectory().toString());
try {
File[] filenames = deleteMatchingFile.listFiles();
if (filenames != null && filenames.length > 0) {
for (File tempFile : filenames) {
if (tempFile.isDirectory()) {
wipeDirectory(tempFile.toString());
tempFile.delete();
} else {
tempFile.delete();
}
}
} else {
deleteMatchingFile.delete();
}
} catch (Exception e) {
Utils.log(e.getMessage());
}
}
private static void wipeDirectory(String name) {
File directoryFile = new File(name);
File[] filenames = directoryFile.listFiles();
if (filenames != null && filenames.length > 0) {
for (File tempFile : filenames) {
if (tempFile.isDirectory()) {
wipeDirectory(tempFile.toString());
tempFile.delete();
} else {
tempFile.delete();
}
}
} else {
directoryFile.delete();
}
}