gpt4 book ai didi

multithreading - 在等待线程完成时显示 progressDialog 2 秒

转载 作者:行者123 更新时间:2023-11-29 00:46:58 25 4
gpt4 key购买 nike

我有一个 Activity ,我在其中调用了一个服务,该服务可能需要一段时间才能完成,直到该服务没有完成,单击的菜单选项应该返回一条错误消息,例如“数据尚未准备好,请重试很快”但是,我想在抛出该错误之前给它几秒钟的时间来完成,在此期间,我想在屏幕上显示一个进度对话框。这是我的代码:

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 秒。如果在那之后它仍然不存在,我会放弃并显示一条错误消息。

问题是屏幕上没有显示进度。我做错了什么?

谢谢,即.

最佳答案

明白了,应该为此使用异步任务,这是代码:

    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);
}

关于multithreading - 在等待线程完成时显示 progressDialog 2 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5872586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com