我正在创建一个应用程序,当您使用用户名和密码登录时,它会从服务器请求信息。服务器的请求需要时间(15-20 秒),同时我想用几个词显示一个旋转条。但是我尝试了很多不同的AsyncTask
课程,但我无法让它发挥作用。它可以获取信息,但会冻结屏幕直到响应。现在我只有一个新线程实现runnable
. 我不确定我需要从代码中的哪个位置调用AsyncTask
.
onClick
触发attemptLogin()
函数:
public void onClick(View view) {
attemptLogin();
}
在attemptLogin()
功能上:
// more code
showProgress(true);
new Thread(new GetServerResponseRunnable()).start();
while (wait) {}
// more code
Runnable 是:
public class GetServerResponseRunnable implements Runnable {
@Override
public void run() {
response = getInfo.getTours(mUsername, mPassword);
wait = false;
}
}
如您所见,它从不同的类中调用另一个函数。这是功能:
public String getTours(String username, String password) {
String req = "GETALLDATA";
String retStr = "";
try {
url = getURL(req, username, password);
sendOutputLine(url, "");
retStr = getReturnString();
Log.d(LoginActivity.DEBUG_TAG, "getTours() return: " + retStr);
} catch (Exception e) {
Log.d(LoginActivity.DEBUG_TAG, "programm bommed client: " + e.getMessage());
}
return retStr;
}
我需要帮助,请。主要是我想做的是:
response = getInfo.getTours(mUsername, mPassword);
wait = false;
同时显示旋转杆。
谢谢
更新:2013 年 2 月 13 日
我使用了这段代码,但我得到了一个
02-13 09:07:16.142: E/AndroidRuntime(1046): java.lang.NullPointerException
在行中:
this.dialog.setMessage(getResources().getString(R.string.login_progress_signing_in));
知道为什么吗?
public class LoginTask extends AsyncTask<Object, Void, String> {
public Context context;
public ProgressDialog dialog;
public void BaseTask(Context context) {
this.context = context;
this.dialog = new ProgressDialog(context);
}
@Override
protected void onPreExecute() {
this.dialog.setMessage(getResources().getString(R.string.login_progress_signing_in));
this.dialog.show();
}
@Override
protected String doInBackground(Object... objects) {
String name = (String) objects[0];
String password = (String) objects[1];
String response = getInfo.getTours(name , password );
return response;
}
@Override
protected void onPostExecute(String response) {
if (dialog != null && dialog.isShowing())
dialog.dismiss();
LoginActivity.response = response;
// process response as you need
}
}