我有一项活动,我在其中调用可能需要一段时间才能完成的服务,直到该服务未完成,单击的菜单选项应返回错误消息,例如“数据尚未准备好,请再试一次不久” 但是,在我抛出错误之前,我想给它几秒钟的时间来完成,在此期间,我想在屏幕上显示progressdialog。 这是我的代码:
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秒。如果在那之后它仍然没有,我放弃并显示错误信息。
问题是进度事物没有出现在屏幕上。 我做错了什么?
感谢, 即
答案 0 :(得分:2)
想通了,应该使用异步任务,这是代码:
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);
}
答案 1 :(得分:0)
你现在所做的至少会造成僵局。
我通常做的是创建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
后调用上面的runnable