gpt4 book ai didi

java - Android 对话框和异步任务

转载 作者:行者123 更新时间:2023-12-02 06:49:59 26 4
gpt4 key购买 nike

我正在尝试制作一个在加载时弹出的进度对话框。我已经弄清楚如何使对话框出现和消失,并且可以更改其中的内容,但我有多个异步任务,并且希望对话框在第一个异步任务启动时出现,然后在最后一个异步任务完成时消失。

有没有办法让对话框知道给定 Activity 的所有异步任务何时完成?我在如何处理这个问题上遇到了问题。感谢您的帮助!

最佳答案

这是一个精确的示例代码,我用它来实现相同的功能。

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

如果您有多个/单独的异步任务类,您可以创建一个静态实用程序类来跟踪和更新计数。

关于java - Android 对话框和异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18161630/

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