受到这个的启发终于结局了如何在AsyncTask运行中终止其操作。

单纯的onCancelled(true)是不行的

下面把代码贴出来~实现了登陆功能。

AsyncTask简介,它使创建需要与用户界面交互的长时间运行的任务变得更简单。相对来说AsyncTask更轻量级一些,适用于简单的异步处理,不需要借助线程和Handler即可实现。

转自stackoverflow

package com.isummation.exampleapp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.net.UnknownHostException; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject; import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; public class UserLogin extends Activity { private EditText etUsername;
private EditText etPassword;
private ProgressDialog progressDialog;
private static final int PROGRESSDIALOG_ID = 0;
private static final int SERVER_ERROR = 1;
private static final int NETWORK_ERROR = 2;
private static final int CANCELLED = 3;
private static final int SUCCESS = 4;
private String ServerResponse;
private LoginTask loginTask; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login); etUsername = (EditText) findViewById(R.id.txt_username);
etPassword = (EditText) findViewById(R.id.txt_password); Button login_button = (Button) this.findViewById(R.id.login_button);
login_button.setOnClickListener(new OnClickListener() {
public void onClick(View viewParam) {
if (etUsername.getText().toString().length() == 0
|| etPassword.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please enter username and password",
Toast.LENGTH_SHORT).show();
} else { //Show dialog by passing id
showDialog(PROGRESSDIALOG_ID);
}
}
});
} protected Dialog onCreateDialog(int id) {
switch(id) {
case PROGRESSDIALOG_ID:
removeDialog(PROGRESSDIALOG_ID); //Please note that forth parameter is true for cancelable Dialog
//Also register cancel event listener
//if the litener is registered then forth parameter has no effect
progressDialog = ProgressDialog.show(UserLogin.this, "Authenticating",
"Please wait...", true, true, new OnCancelListener(){ public void onCancel(DialogInterface dialog) {
//Check the status, status can be RUNNING, FINISHED and PENDING
//It can be only cancelled if it is not in FINISHED state
if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
loginTask.cancel(true);
}
});
break;
default:
progressDialog = null;
}
return progressDialog;
} @Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case PROGRESSDIALOG_ID:
//check if any previous task is running, if so then cancel it
//it can be cancelled if it is not in FINISHED state
if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
loginTask.cancel(true);
loginTask = new LoginTask(); //every time create new object, as AsynTask will only be executed one time.
loginTask.execute();
}
} class LoginTask extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... unused) {
try {
ServerResponse = null; //don't forget to make it null, as task can be called again
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(
getString(R.string.WebServiceURL)
+ "/cfc/iphonewebservice.cfc?returnformat=json&method=validateUserLogin&username="
+ URLEncoder.encode(etUsername.getText()
.toString(), "UTF-8")
+ "&password="
+ URLEncoder.encode(etPassword.getText()
.toString(), "UTF-8"));
httpClient.getParams().setParameter(
CoreProtocolPNames.USER_AGENT,"Some user agent string"); //call it just before you make server call
//calling after this statement and canceling task will no meaning if you do some update database kind of operation
//so be wise to choose correct place to put this condition
//you can also put this condition in for loop, if you are doing iterative task //now this very important
//if you do not put this condition and not maintaining execution, then there is no meaning of calling .cancel() method
//you should only check this condition in doInBackground() method, otherwise there is no logical meaning
if (isCancelled())
{
publishProgress(CANCELLED); //Notify your activity that you had canceled the task
return (null); // don't forget to terminate this method
}
HttpResponse response = httpClient.execute(httpGet,
localContext); BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
ServerResponse = reader.readLine();
publishProgress(SUCCESS); //if everything is Okay then publish this message, you may also use onPostExecute() method
} catch (UnknownHostException e) {
removeDialog(PROGRESSDIALOG_ID);
e.printStackTrace();
publishProgress(NETWORK_ERROR);
} catch (Exception e) {
removeDialog(PROGRESSDIALOG_ID);
e.printStackTrace();
publishProgress(SERVER_ERROR);
}
return (null);
} @Override
protected void onProgressUpdate(Integer... errorCode) {
switch (errorCode[0]) {
case CANCELLED:
removeDialog(PROGRESSDIALOG_ID);
Toast.makeText(getApplicationContext(), "Cancelled by user",
Toast.LENGTH_LONG).show();
break;
case NETWORK_ERROR:
removeDialog(PROGRESSDIALOG_ID);
Toast.makeText(getApplicationContext(), "Network connection error",
Toast.LENGTH_LONG).show();
break;
case SERVER_ERROR:
removeDialog(PROGRESSDIALOG_ID);
Toast.makeText(getApplicationContext(), "Server error",
Toast.LENGTH_LONG).show();
break;
case SUCCESS:
removeDialog(PROGRESSDIALOG_ID);
try {
if (ServerResponse != null) {
JSONObject JResponse = new JSONObject(ServerResponse);
String sMessage = JResponse.getString("MESSAGE");
int success = JResponse.getInt("SUCCESS");
if (success == 1) {
//proceed further //you may start new activity from here
//after that you may want to finish this activity
UserLogin.this.finish(); //Remember when you finish an activity, it doesn't mean that you also finish thread or AsynTask started within that activity
//So you must implement onDestroy() method and terminate those threads.
} else {
//just showing invalid username password from server response
Toast.makeText(getApplicationContext(), sMessage,
Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e){
Toast.makeText(getApplicationContext(), "Server error",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
break;
}
} @Override
protected void onPostExecute(Void unused) { }
} @Override
protected void onDestroy(){
//you may call the cancel() method but if it is not handled in doInBackground() method
if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
loginTask.cancel(true);
super.onDestroy();
}
}

原文出处:http://www.ericyue.info/archive/stop-asynctask#more-1117

解决如何让AsyncTask终止操作的更多相关文章

  1. IE无法打开internet网站已终止操作的解决的方法

    用IE内核浏览器的朋友,或许不经意间会碰到这样滴问题: 打开某个网页时,浏览器“嘣”跳出一个提示框“Internet Explorer无法打开Internet 站点...已终止操作”.而大多数情况下该 ...

  2. 解决IE6已终止操作问题

    令人崩溃的IE6问题再次出现,打开某个页面时,弹出提示框“Internet Explorer无法打开Internet 站点...已终止操作”.    查了一下资料,感觉“因为js(一个比较复杂的js) ...

  3. IE6“无法打开站点,已终止操作”提示的解决

    今天遇到一个问题,网站在IE 6下面打开会提示:Internet Explorer无法打开站点XXX.已终止操作. 先介绍一下网上常见的解决方法. 因为在页面还没有ready的时候就调用了htmlOb ...

  4. 关于日历控件My97DatePicker 在IE6下出现“无法打开站点,已终止操作”

    1.My97DatePicker 官方:http://www.my97.net2.在IE6下出现“无法打开站点,已终止操作”的解决办法(转): .这是一个绝对有效的方法,但是会丢失跨越iframe的特 ...

  5. 使用<base target="_self" /> IE6 cann't open the Internet site 已终止操作

    今日发现一个问题,我的网页需要用到<base target="_self" />,经测试IE8,9  谷歌   火狐全都正常,但是IE6 showModalDialog ...

  6. ie6 无法显示网页 已终止操作

    已终止操作原因: 在文件加载完成之前执行了dom操作,如appendChild, innerHTML等 解决办法: ready后再执行

  7. java8-10-Stream的终止操作

      Stream的终止操作   * allMatch 是否匹配所有 * anyMatch 是否匹配一个 * noneMatch 是否没有匹配一个 * findFirst 返回第一个   * count ...

  8. jm解决乱码问题-参数化-数据库操作-文件上传下载

    jm解决乱码问题-参数化-数据库操作-文件上传下载 如果JM出果运行结果是乱码(解决中文BODY乱码的问题) 找到JM的安装路径,例如:C:\apache-jmeter-3.1\bin 用UE打开jm ...

  9. m_Orchestrate learning system---十、解决bug最根本的操作是什么

    m_Orchestrate learning system---十.解决bug最根本的操作是什么 一.总结 一句话总结:多学多练,遇到bug超级轻松 1.如何查看js代码的异常? 开发者选项里面可以查 ...

随机推荐

  1. C#。1 数据类型,常量变量,类型转换

    C#. 一.数据类型 1,字符串类型(string) .放入一串字符串,需要用""引起来. 列如: string a ="999"; 2,整型 (int).   ...

  2. Linq 学习(1) 概述

    本篇简单回顾C#语言集合操作的变化,通过与Linq对等的面向对象的语法来认识Linq.Linq是Language Integrated Query, 初识Linq感觉跟SQL Server的Tsql很 ...

  3. Android-为何以及如何保存Fragment实例

    在安卓开发中,由于旋转设备会造成配置改变进而导致Activity实例被摧毁(当然也包括Activity托管的Fragment).Activity或Fragment实例被摧毁自然也就让Model被摧毁, ...

  4. MYSQL显示数据库内每个表拥有的触发器

    一  所有数据库->所有触发器: SELECT * FROM information_schema.triggers; 二  当前数据库->当前所有触发器(假设当前数据库为gmvcs_ba ...

  5. uva 10167 - Birthday Cake

    题解:由于解太多,随机抓 A.B, 只要有符合就行了: (首先,Ax+By=0必须表示直线,即A.B不能同时为0:另外,要注意到直线不能过输入中的2N个点:检测点在直线的哪一侧,只需要简单的线性规划的 ...

  6. 什么叫CallBack函数,怎么用回调函数?

    JQuery众多常用方法中很经常会用到回调函数, 理解好js callback函数定义及用法,我们就可以利用callback函数帮我们做很多事情啦! A callback is a function ...

  7. Python一路走来 DAY15 Javascript

    JavaScript是一门编程语言,浏览器内置了JavaScript语言的解释器,所以在浏览器上按照JavaScript语言的规则编写相应代码之,浏览器可以解释并做出相应的处理. 一 如何编写     ...

  8. apscheduler的使用

    最近一个程序要用到后台定时任务,看了看python后台任务,一般2个选择,一个是apscheduler,一个celery.apscheduler比较直观简单一点,就选说说这个库吧.网上一搜索,晕死,好 ...

  9. 使用QtScript库解析Json数组例子

    本文转载自:http://blog.sina.com.cn/s/blog_671732440100uwxh.html 使用qtscipt库解析json数组首先在工程文件中加 QT        += ...

  10. fuck WPFG.org

    今天一旦进入国外网站,就立刻跳转到WPFG.org.可能DNS被劫持污染了吧.用OpenDNS就行了.然后就没有这回事发生了 参考以下: https://www.opendns.com https:/ ...