当 AsyncTask
在 onPreExecute() 中启动时,我试图让 ProgressDialog
出现,在 doInBackground()
中做一些事情,并在 onPostExecute()
中关闭 ProgressDialog
。
在我看来,这应该是简单直接的,但我一定做错了什么。
每当我在我的应用程序中单击 Button
进行更新并且 AsyncTask
运行时,应用程序会卡住,稍等片刻,然后 ProgressDialog
立即出现和消失,完成了 doInBackground()
中的工作。我不明白为什么 onPreExecute()
在 doInBackground()
之后运行,但这似乎正是这里发生的事情。这是代码:
public class UpdateStats extends AsyncTask<CatchAPI, Void, String[]> {
private ProgressDialog pdia;
private Context context;
private APIParser parser = new APIParser();
public UpdateStats(Context contexts) {
context = contexts;
}
@Override
protected void onPreExecute() {
pdia = new ProgressDialog(context);
pdia.setMessage("Loading...");
pdia.show();
super.onPreExecute();
}
@Override
protected String[] doInBackground(CatchAPI... api) {
String apiOutput = api[0].returnAPI();
return new String[] {
parser.getPoolName(apiOutput),
parser.getHashRate(apiOutput),
parser.getWorkers(apiOutput),
parser.getSharesThisRound(apiOutput)
};
}
@Override
protected void onPostExecute(String[] result) {
pdia.dismiss();
super.onPostExecute(result);
}
}
以及 MainActivity 中的 onClickListener:
updateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String[] text = null;
UpdateStats updater = new UpdateStats(context);
try {
text = updater.execute(api).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
poolNameTV.setText(text[0]);
hashRateTV.setText(text[1]);
workersTV.setText(text[2]);
sharesThisRoundTV.setText(text[3]);
}
});
最佳答案
在这里:
text = updater.execute(api).get(); //<<<
您正在调用 AsyncTask.get()卡住 UI 线程执行,直到 doInBackground
执行未完成。执行 AsyncTask 为:
updater.execute(api)
并更新 onPostExecute
中的 UI 元素,它在 doInBackground
执行完成时调用 UI Thread。
@Override
protected void onPostExecute(String[] result) {
pdia.dismiss();
// update UI here..
poolNameTV.setText(result[0]);
hashRateTV.setText(result[1]);
workersTV.setText(result[2]);
sharesThisRoundTV.setText(result[3]);
super.onPostExecute(result);
}
关于Android - AsyncTask - onPreExecute() 在 doInBackground() 完成后运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16391372/