我想用旋转滚轮显示简单的进度对话框,同时从SD卡中删除文件夹。我有一段代码:
ProgressDialog dialog = ProgressDialog.show(this, "",
"Please wait for few seconds...", true);
private void deleteCache() {
File f = new File(Environment.getExternalStorageDirectory()
.getAbsoluteFile() + Constants.DATA_DIR);
deleteDirectory(f);
dialog.dismiss();
}
private void deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}
应该在deleteDirectory(f);
之前显示对话框,并在结束后将其取消。但是我没有看到任何对话框,但是文件夹被删除了。
答案 0 :(得分:4)
这个答案也在StakcOverflow上。使用AsyncTask将在不同的线程上运行并有三个阶段...一个你将加载轮子的前一个和你将在完成后将它解雇的帖子...然后是实际的背景工作
答案 1 :(得分:2)
private void deleteCache() {
ProgressDialog dialog = ProgressDialog.show(this, "",
"Please wait for few seconds...", true);
Runnable myRun = new Runnable() {
public void run() {
File f = new File(Environment.getExternalStorageDirectory()
.getAbsoluteFile() + Constants.DATA_DIR);
deleteDirectory(f);
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
}
});
}
}
}
private void deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}
答案 2 :(得分:1)
像这样修改你的代码,
ProgressDialog dialog = ProgressDialog.show(this, "",
"Please wait for few seconds...", true);
new Thread(new Runnable() {
public void run() {
File f = new File(Environment.getExternalStorageDirectory()
.getAbsoluteFile() + Constants.DATA_DIR);
deleteDirectory(f);
private void deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}
handler.sendEmptyMessage(0);
}
}).start();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
progressDialog.dismiss();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
};
我不确定为什么会这样。由于您的代码在单个线程中执行所有操作,因此progressdialog不会快速显示。因此,尝试在单独的线程中处理其他事情来处理这个问题。