我有一个活动,我调用一个服务,可能需要一段时间才能完成,直到该服务没有完成,点击的菜单选项应该返回一个错误消息,如"数据尚未准备好,请稍后再试"然而,我想在抛出错误之前给它几秒钟的时间来完成,在这段时间里,我想在屏幕上显示一个进度对话框。下面是我的代码:
if(calculatedValue.equals(NOT_YET_CALCULATED)){
//show progress dialog
ProgressDialog progress = ProgressDialog.show(this, "", getResources().getString(R.string.wait), true);
long timeStarted = System.currentTimeMillis();
while(calculatedValue.equals(NOT_YET_CALCULATED) && System.currentTimeMillis() - timeStarted < 1500){
// wait for at most 1.5 seconds
}
progress.dismiss();
if(calculatedValue.equals(NOT_YET_CALCULATED)){
//if it's still not there, there's probably a problem, show generic alert dialog
AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setTitle(R.string.not_yet_calulated_alert_title);
dialog.setMessage(getResources().getString(R.string.not_yet_calulated_alert_message));
dialog.show();
}else{
startActivity(j);
}
}else{
startActivity(j);
}
让我解释一下:我检查这个值是否存在,如果不存在,我就会显示一个进度图标,持续1.5秒。如果在此之后它仍然不存在,我放弃并显示一个错误消息。
问题是进度项没有显示在屏幕上。我做错了什么?
谢谢,e。
算出来了,应该使用异步任务,下面是代码:
if(calculatedValue.equals(NOT_YET_CALCULATED)){
//show progress dialog
final ProgressDialog progress = ProgressDialog.show(this, "", getResources().getString(R.string.wait), true);
AsyncTask<Void, Void, Boolean> waitForCompletion = new AsyncTask<Void, Void, Boolean>(){
@Override
protected Boolean doInBackground(Void... params) {
long timeStarted = System.currentTimeMillis();
while(calculatedValue.equals(NOT_YET_CALCULATED) && System.currentTimeMillis() - timeStarted < 1500){
// wait for 1.5 ms
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Log.e(TAG, "thread interrupted", e);
}
}
progress.dismiss();
return calculatedValue.equals(NOT_YET_CALCULATED);
};
@Override
protected void onPostExecute(Boolean result) {
if(result == true){
AlertDialog dialog = new AlertDialog.Builder(TodayActivity.this).create();
dialog.setTitle(R.string.not_yet_calulated_alert_title);
dialog.setMessage(getResources().getString(R.string.not_yet_calulated_alert_message));
dialog.show();
}else{
i.putExtra(Constants.AMOUNT, Integer.parseInt(calculatedValue));
startActivity(i);
}
}
};
waitForCompletion.execute(null, null, null);
}else{
i.putExtra(Constants.AMOUNT, Integer.parseInt(calculatedValue));
startActivity(i);
}
您现在所做的至少会导致死锁。
我通常做的是像你现在做的那样创建progressdialog,同时启动另一个线程,在这种情况下等待1.5秒,然后停止progressdialog。
例如 private Runnable waitforcompletion = new Runnable()
{
@Override
public void run()
{
while(calculatedValue.equals(NOT_YET_CALCULATED) && System.currentTimeMillis() - timeStarted < 1500){
Thread.sleep(10);
}
progress.dismiss();
}
};
在创建progressdialog