【发布时间】:2011-05-08 03:35:52
【问题描述】:
我正在编写一个应用程序,它在很多时候会尝试从网站检索帐户信息。我想编写一个函数(“getAccount()”)来执行以下操作:
- 显示进度对话框
- 致电网站
- 等待回复
- 清除 ProgressDialog
- 前四步完成后,将控制权返回给调用函数
我从页面获取数据没有问题;我遇到的问题是整个“显示对话框/等待完成/将控制权返回给调用函数”部分。要么 ProgressDialog 根本不显示,要么函数在从站点发出数据请求后立即返回给调用者,而没有给它足够的时间来检索数据。
任何帮助将不胜感激。
编辑:我在下面添加了一些关于 AsyncTask 的代码。请注意,我在grabURL() 中有MsgBox("done") 行;这只是一个 Toast 调用。当我运行这段代码时,“完成”会在 HTTP 请求仍在进行时弹出。此 MsgBox 行仅存在,因此我可以查看 grabURL 是否正确等待 GrabURL 完成(它不是)。
public void grabURL() {
new GrabURL().execute();
MsgBox("done");
}
private class GrabURL extends AsyncTask<String, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(MyContext);
protected void onPreExecute() {
Dialog.setTitle("Retrieving Account");
Dialog.setMessage("We're retrieving your account information. Please wait...");
Dialog.show();
}
protected Void doInBackground(String... urls) {
try {
// Get account info from the website
String resp = GetPage(ThePage); // I have this classed out elsewhere
// Some other code that massages the data
AccountRetrievalSuccess = true;
} catch (Exception e) {
AccountRetrievalSuccess = false;
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
}
}
【问题讨论】:
-
AsyncTask, AsyncTask, AsyncTask
-
你有没有想过这个问题?我想做完全相同的事情,我很惊讶我找不到一个简单的解决方案。 stackoverflow.com/questions/15179517/…