AsyncTask 的想法不是“获得”结果,而是在不阻塞 UI 的情况下在后台发生一些事情。您的方法将阻塞 UI 线程,直到服务器返回响应,应用程序将被阻塞,如果该状态保持超过 5 秒,用户将看到 ANR
但要回答您的问题:
为了从 AsyncTask 获得布尔结果,您需要扩展正确的类,在您的情况下是:AsyncTask<String, Void, Boolean>,因为 AsyncTask 类型如下:
异步任务使用的三种类型如下:
Params,执行时发送给任务的参数类型。
Progress,后台计算时发布的进度单位类型。
Result,后台计算结果的类型。
所以要回答你的问题,你的代码将是:
//USAGE
Login l = new Login();
Boolean valid = l.execute("user", "pass").get();
/* but the UI thread will be
blocked, meaning the following code will not be executed until the variable
valid is populated */
//AsyncTask
public class Login extends AsyncTask<String, Void, Boolean> {
public Login(Application application){
repository = new Repository(application);
}
@Override
protected Boolean doInBackground(String... strings){
try {
user = repository.getUser(strings[0], strings[1]);
if (user != null)
return true; //wont work
else {
return false;
}
}
catch(Exception e){
return null;
}
}
protected void onPostExecute(Boolean result) {
// this method is no longer needed since you will get the result directly
// from the doInBackground method
}
也没有实际可行的解决方案:
我建议每次用户想要登录应用程序时都应该显示一个progressDialog 窗口,通知用户它必须执行一项耗时的任务,并在该过程完成后通知用户状态。
为此,请使用以下代码:
//USAGE
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Login l = new Login();
l.execute("user", "pass");
/* but the UI thread will be
blocked, meaning the following code will not be executed until the
variable valid is populated */
}
public void userLoggedIn() {
// do something when a user loggs in sucessfully
}
public void wrongCredentials() {
// alert the user that he didn't put in the correct credentials
}
//AsyncTask
public class Login extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// show a dialog window here when the AsyncTask starts
}
@Override
protected Boolean doInBackground(String... strings){
try {
user = repository.getUser(strings[0], strings[1]);
if (user != null)
return true; //wont work
else {
return false;
}
}
catch(Exception e){
return null;
}
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
// dismiss the dialog window here after the AsyncTask finishes
if (aBoolean) {
userLoggedIn();
} else {
wrongCredentials();
}
}
}