問題描述
事情應該很簡單,但在大多數情況下,在 Android 中并非如此.如果用戶在我的應用程序中選擇該選項,我需要格式化 SD 卡.如果它已經在操作系統中,不要問我為什么需要這樣做......不切實際,但這是我需要實現的要求.您可能知道,設置存儲擦除SD卡中有一個選項.我看了一下 froyo 源代碼,它是這樣的:
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.
推薦答案
我在這里找不到關于 SO 的問題,但它有一個可行的解決方案.所以所有的功勞都歸于那個人;)
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();
}
}
這篇關于在 Android 中格式化 SD 卡的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!