【发布时间】:2014-06-17 22:33:37
【问题描述】:
我有一段代码连接到服务器然后登录。在执行这两个任务(连接到服务器和登录)时,一个进度对话框出现。
final ProgressDialog pd = new ProgressDialog(getActivity());
pd.setIndeterminate(true);
pd.setCancelable(false);
// While connecting to the server, the dialog should say the following:
pd.setTitle("Connecting...");
pd.setMessage("Connecting to " + hostname + "...");
pd.show();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
// First task is executed. Progress dialog should say "Connecting..."
executeTask1();
// When the first task (connecting to server) is ready, I want the title
// and the message of the progress dialog to be changed into this:
pd.setTitle("Logging in"); //// MARKED LINE, see below. ////
pd.setMessage("Trying to log in to server...");
// Second task is executed.
executeTask2();
// Shows a screen and dismisses the ProgressDialog.
showScreen(ScreenConstant.LIST_RESIDENTS);
pd.dismiss();
}
catch (Exception exc) { }
}
}
但是我遇到了两个问题:
- 执行 MARKED LINE(见上文)时会引发
RuntimeException:“只有创建视图层次结构的原始线程才能接触其视图” - 登录任务从服务器获得响应,但该响应是异步的。
我希望ProgressDialog 在执行连接尝试时显示文本“正在连接...”。连接成功后,我希望将进度对话框的文本更改为“正在登录...”,同时正在执行登录尝试。
现在我应该如何做到这一点?
编辑
注意executeTask2() 触发一个任务在一个不同的线程中运行;它向服务器发送一个登录请求,因此我需要等到该线程准备好时向我发出信号。
【问题讨论】:
标签: android android-asynctask progressdialog ui-thread