这是取消AsyncTask
的正确方法吗?
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RequestTask requestTask = new RequestTask();
requestTask.execute();
while(requestTask.isCancelled()) {
if (requestTask.isCancelled())
Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
});
我在
if
循环中使用了while
。我真的不知道这些陈述是否正确。@Override
protected String doInBackground(String... strings) {
String[] kx_var_array = new String[10];
String returnString = "";
final TelephonyManager telephonyManager = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
final String deviceId, deviceSerial, deviceAndroidId;
deviceId = "" + telephonyManager.getDeviceId();
deviceSerial = "" + telephonyManager.getSimSerialNumber();
deviceAndroidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
while (!isCancelled()){
if (cd.isConnectingToInternet()) {
Context context = getApplicationContext();
final HttpClient httpClient = new DefaultHttpClient();
//email und passwort aus den Feldern in Variablen speichern
String URLEmail = email.getText().toString().replace(" ", "");
String URLPassword = password.getText().toString();
if (URLEmail.length() > 128) {
Toast.makeText(context, "Email-Adresse ist zu Lang!", Toast.LENGTH_SHORT).show();
return null;
} else if (URLPassword.length() > 64) {
Toast.makeText(context, "Passwort ist zu Lang!", Toast.LENGTH_SHORT).show();
return null;
}
//Response vom Server
HttpGet httpGet = new HttpGet(URL);
//HttpResponse httpResponse = httpClient.execute(new HttpGet(URL));
//Empfange Daten
//returnString = EntityUtils.toString(httpResponse.getEntity());
returnString = null;
if (returnString == null) {
cancel(true);
dialog.dismiss();
break;
}
}
}
return returnString;
}
protected void onPostExecute(String result) {
if (dialog.isShowing()) dialog.dismiss();
if (result != null) setKx_map(result);
else {
Toast.makeText(getApplicationContext(), "Laden fehlgeschlagen", Toast.LENGTH_SHORT).show();
finish();
}
为了测试目的,我设置了
returnString == null
。我想确定如果我没有从Server那里得到任何东西,
AsyncTask
将停止而不用更多的时间和资源。 最佳答案
上面的代码段存在一些错误:
首先,不要从email
中访问password
或doInBackground
-在单独的线程上执行,并且可以创建竞争条件。在创建AsyncTask
之前,从视图中获取值,然后将其作为参数传递。
其次,为什么要循环播放?您的代码段似乎反复无限制地将电子邮件和密码发送到服务器,直到收到空响应为止。
第三,在您的第一个代码段中,while
循环将永远不会真正执行:requestTask.isCancelled()
在某些内容调用cancel()
之前,不会为真。
在我看来,就像您的第一个代码片段一样,您正在尝试等待requestTask
完成处理,然后在失败时打印一条消息。那是行不通的,也不应该使它生效,因为它违反了AsyncTask
的要点:执行某些任务而不阻塞其余代码的执行。到AsyncTask
甚至开始执行时,第一个代码段中的最后几行代码将成为该线程执行过程中的遥远内存。如果要打印错误消息,而使用AsyncTask
表示状态,请在cancel()
中覆盖onCancelled
。
关于android - 在Android中取消Asynctask的正确方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31558519/