我正在尝试创建一个在加载内容时弹出的进度对话框。我已经弄清楚如何使对话框出现和消失,并且可以更改其中的内容但我有多个异步任务,并希望在第一个异步任务启动时显示对话框,然后在最后一个异步任务完成时消失。
对话框是否有办法知道给定活动的所有异步任务何时完成?我在如何解决这个问题上遇到了问题。谢谢你的帮助!
答案 0 :(得分:2)
以下是我用来实现相同功能的精确示例代码。
public class LoginActivity extends Activity
{
public static String TAG = "Login_Activity: ";
private EditText usernameEditText;
private EditText passwordEditText;
private ProgressDialog progress_dialog;
private int taskCount = 0;
private void updateTaskCount(int value)
{
taskCount += value;
if(progress_dialog != null && taskCount == 0)
{
progress_dialog.dismiss();
}
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
usernameEditText = (EditText) findViewById(R.id.login_username);
passwordEditText = (EditText) findViewById(R.id.login_password);
progress_dialog = new ProgressDialog(this);
}
public void LoginClick(View view)
{
String URL = "http://SOME.com/api/Members?Username=" +
usernameEditText.getText().toString()+ "&Password=" +
passwordEditText.getText().toString();
progress_dialog.setMessage("Authenticating. Please wait...");
progress_dialog.setCancelable(false);
progress_dialog.show();
new AuthenticateUserFromServer().execute(URL);
updateTaskCount(1);
new NotifyWebService ().execute("some other url");
updateTaskCount(1);
}
protected void onDestroy()
{
progress_dialog.dismiss();
super.onDestroy();
}
@Override
protected void onPause()
{
progress_dialog.dismiss();
super.onPause();
}
private class AuthenticateUserFromServer extends AsyncTask <String, Void, String>
{
protected String doInBackground(String... urls)
{
return Utility.readJSONFromWebService(urls[0]);
}
protected void onPostExecute(String result)
{
// do other stuff
updateTaskCount(-1);
}
}
private class NotifyWebService extends AsyncTask <String, Void, String>
{
protected String doInBackground(String... urls)
{
return Utility.readJSONFromWebService(urls[0]);
}
protected void onPostExecute(String result)
{
// do other stuff
updateTaskCount(-1);
}
}
}
如果您有多个/单独的异步任务类,您可以创建一个静态实用程序类来跟踪和更新计数。