【发布时间】:2012-10-02 13:44:51
【问题描述】:
我必须在我的 Android 应用程序中等待几秒钟,我想在此期间显示一个进度条,我该怎么做?
我试过这个代码:
public boolean WaitTask() {
pDialog = ProgressDialog.show(context,null, "Lädt..",true);
new Thread() {
public void run() {
try{
// just doing some long operation
sleep(2000);
} catch (Exception e) { }
pDialog.dismiss();
}
}.start();
return true;
}
但进度条会立即关闭,无需等待两秒钟。我的问题在哪里?
进度条应该类似于 Android 开发者在this 网站中显示的活动圈。
更新 异步任务
private class WaitTime extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
mDialog.show();
}
protected void onPostExecute() {
mDialog.dismiss();
}
@Override
protected void onCancelled() {
mDialog.dismiss();
super.onCancelled();
}
@Override
protected Void doInBackground(Void... params) {
long delayInMillis = 2000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
mDialog.dismiss();
}
}, delayInMillis);
return null;
}
}
我这样称呼它:
mDialog = new ProgressDialog(CreateProject.this);
mDialog = ProgressDialog.show(context,null, "Lädt..",true);
WaitTime wait = new WaitTime();
wait.execute();
【问题讨论】:
-
也许这篇文章:stackoverflow.com/questions/2798443/… 会有所帮助
-
我尝试了前两种解决方案,但均未成功。进度条立即消失...
-
根据您的 asynctask 更新:定时器的计划任务在后台运行,因此在 doInBackground 中计划定时器后立即调用 onPostExecute,因此立即关闭对话框,有关如何处理对话框的示例,请参见我的答案计时器。
标签: android progress-bar wait