Java 等待AsyncTask完成其onPostExecute(),同时保持UI线程为ProgressDialog打开
我已经读了很多关于异步任务的书,但是我想不出什么。我启动了一个AsyncTask,用于数据库请求的HttpURLConnection。数据库工作是在doInBackground()中完成的,我有一个在UI线程上运行的ProgressDialog,它只是显示它正在加载。但是,一旦doInBackground()完成,我的代码就会继续,即使在onPostExecute()中有一些事情需要在代码继续之前发生 有没有办法使AsyncTask保持异步,这样我就可以运行ProgressDialog,同时在doInBackgroun()中执行数据库工作,并让它等待调用onPostExecute()后再继续 澄清: 我不能只在onPostExecute()调用中调用函数。启动时,会打开一个AlertDialog,以便用户输入用户名和密码,以便登录。当他们点击login时,AsyncTask运行。我需要AlertDialog知道onPostExecute()何时完成,以便关闭它。否则我会被它缠住 以下是AlertDialog开头的代码:Java 等待AsyncTask完成其onPostExecute(),同时保持UI线程为ProgressDialog打开,java,android,android-asynctask,Java,Android,Android Asynctask,我已经读了很多关于异步任务的书,但是我想不出什么。我启动了一个AsyncTask,用于数据库请求的HttpURLConnection。数据库工作是在doInBackground()中完成的,我有一个在UI线程上运行的ProgressDialog,它只是显示它正在加载。但是,一旦doInBackground()完成,我的代码就会继续,即使在onPostExecute()中有一些事情需要在代码继续之前发生 有没有办法使AsyncTask保持异步,这样我就可以运行ProgressDialog,同时在d
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setCancelable(false);
final EditText usernameInput = new EditText(context);
usernameInput.setHint("Username");
final EditText passwordInput = new EditText(context);
passwordInput.setHint("Password");
passwordInput.setTransformationMethod(PasswordTransformationMethod.getInstance());
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(usernameInput);
layout.addView(passwordInput);
alert.setView(layout);
alert.setTitle("Login");
alert.setPositiveButton("Login", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
String username = usernameInput.getText().toString();
String password = passwordInput.getText().toString();
if (username != "" && password != "")
{
Database database = new Database(currActivity);
database.Login(username, password);
if (database.IsLoggedIn())
{
SharedPreferences prefs = currActivity.getSharedPreferences("Preferences", currActivity.MODE_PRIVATE);
prefs.edit().putBoolean("Logged In", true).commit();
dialog.cancel();
}
else ShowLoginAlert(context);
}
}
});
alert.show();
以下是我的登录代码:
public void Login(String username, String password)
{
try
{
new AsyncLogin().execute(username, password).get();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e1)
{
e1.printStackTrace();
}
}
private class AsyncLogin extends AsyncTask<String, String, String>
{
private static final int READ_TIMEOUT = 1000000;
private static final int CONNECTION_TIMEOUT = 1000000;
private URL url = null;
private HttpURLConnection conn = null;
ProgressDialog loading = new ProgressDialog(currActivity);
@Override
protected void onPreExecute()
{
super.onPreExecute();
loading.setMessage("\tLoading...");
loading.setCancelable(false);
loading.show();
}
@Override
protected String doInBackground(String... params)
{
try
{
url = new URL("http://mysite/myscript.php");
}
catch (MalformedURLException e)
{
e.printStackTrace();
return "Malformed URL Exception.";
}
try
{
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username", params[0])
.appendQueryParameter("password", params[1]);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
conn.connect();
}
catch (IOException e1)
{
e1.printStackTrace();
return "Connection Exception.";
}
try
{
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK)
{
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
{
result.append(line);
}
return result.toString();
}
else return "Unsuccessful data retrieval.";
}
catch (IOException e2)
{
e2.printStackTrace();
return "Response Exception.";
}
finally
{
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
loading.dismiss();
if (result.equalsIgnoreCase("true"))
{
// Successfully logged in
SetIsLoggedIn(true);
Toast.makeText(currActivity, "Successfully logged in.", Toast.LENGTH_LONG).show();
}
else
{
// Incorrect credentials
SetIsLoggedIn(false);
Toast.makeText(currActivity, "Incorrect credentials.", Toast.LENGTH_LONG).show();
}
}
}
public void登录(字符串用户名、字符串密码)
{
尝试
{
新建AsyncLogin().execute(用户名、密码).get();
}
捕捉(中断异常e)
{
e、 printStackTrace();
}
捕获(执行异常e1)
{
e1.printStackTrace();
}
}
私有类AsyncLogin扩展了AsyncTask
{
私有静态最终整型读取超时=1000000;
私有静态最终整数连接\u超时=1000000;
私有URL=null;
私有HttpURLConnection conn=null;
ProgressDialog加载=新建ProgressDialog(活动);
@凌驾
受保护的void onPreExecute()
{
super.onPreExecute();
正在加载.setMessage(“\t正在加载…”);
加载。可设置可取消(false);
loading.show();
}
@凌驾
受保护的字符串doInBackground(字符串…参数)
{
尝试
{
url=新url(“http://mysite/myscript.php");
}
捕获(格式错误)
{
e、 printStackTrace();
返回“格式错误的URL异常。”;
}
尝试
{
conn=(HttpURLConnection)url.openConnection();
conn.setReadTimeout(读取超时);
连接设置连接超时(连接超时);
conn.setRequestMethod(“POST”);
conn.setDoInput(真);
连接设置输出(真);
Uri.Builder=新的Uri.Builder()
.appendQueryParameter(“用户名”,参数[0])
.appendQueryParameter(“密码”,参数[1]);
字符串查询=builder.build().getEncodedQuery();
OutputStream os=conn.getOutputStream();
BufferedWriter writer=新的BufferedWriter(新的OutputStreamWriter(os,“UTF-8”));
writer.write(查询);
writer.flush();
writer.close();
连接();
}
捕获(IOE1异常)
{
e1.printStackTrace();
返回“连接异常”;
}
尝试
{
int responseCode=conn.getResponseCode();
if(responseCode==HttpURLConnection.HTTP\u确定)
{
InputStream input=conn.getInputStream();
BufferedReader reader=新的BufferedReader(新的InputStreamReader(输入));
StringBuilder结果=新建StringBuilder();
弦线;
而((line=reader.readLine())!=null)
{
结果。追加(行);
}
返回result.toString();
}
否则返回“数据检索失败”;
}
捕获(IOE2异常)
{
e2.printStackTrace();
返回“响应异常”;
}
最后
{
连接断开();
}
}
@凌驾
受保护的void onPostExecute(字符串结果)
{
super.onPostExecute(结果);
loading.dispose();
if(result.equalsIgnoreCase(“true”))
{
//已成功登录
SetIsLoggedIn(真);
Toast.makeText(currActivity,“已成功登录)”,Toast.LENGTH_LONG.show();
}
其他的
{
//不正确的凭证
SetIsLoggedIn(假);
Toast.makeText(currActivity,“不正确的凭据”,Toast.LENGTH_LONG.show();
}
}
}
您可以通过以下方式执行此操作:
class main extends Activity {
class Something extends AsyncTask<String, Integer, String> {
protected void onPreExecute() {
// showProgressDialog
}
protected String doInBackground(String... params) {
// Do your heavy stuff...
return null;
}
protected void onPostExecute(String result) {
// close your progress dialog and than call method which has
// code you are wishing to execute after AsyncTask.
}
}
类主扩展活动{
将某个类扩展为异步任务{
受保护的void onPreExecute(){
//showProgressDialog
}
受保护的字符串doInBackground(字符串…参数){
//做你的重东西。。。
返回null;
}
受保护的void onPostExecute(字符串结果){
//关闭进度对话框,然后调用具有
//您希望在异步任务后执行的代码。
}
}
}我认为您想要的不是很难,您可以使用以下代码:
class main extends MainActivity {
class SampleAsyncTask extends AsyncTask<String, Integer, String> {
protected void onPreExecute() {
// ProgressDialog
}
protected String doInBackground(String... params) {
// Do your database code...
return null;
}
protected void onPostExecute(String result) {
// close progress dialog
// code you are wishing to execute after AsyncTask.
}
}
}
class main扩展main活动{
类SampleAsyncTask扩展异步任务{
受保护的void onPreExecute(){
//进展对话
}
受保护的字符串doInBackground(字符串…参数){
//你的数据库代码。。。
返回null;
}
受保护的void onPostExecute(字符串结果){
//关闭进度对话框
//您希望在异步任务后执行的代码。
}
}
}
如果我理解正确,您有两个对话框(进度和警报),您希望在收到登录响应后关闭其中一个对话框,并保留另一个对话框,直到数据库工作完成
如果是的话,我想你需要