受到这个的启发终于结局了如何在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. python字符串连接方式(转)

    在python中有很多字符串连接方式,今天就在这里具体总结一下: ①.最原始的字符串连接方式:str1 + str2②.python 新字符串连接语法:str1, str2③.奇怪的字符串方式:str ...

  2. Handler Looper 原理 详解

    演示代码 public class MainActivity extends ListActivity {     private TextView tv_info;     private CalT ...

  3. jQuery下的显示和隐藏

    因为太久没更新了,所以来放一点没意思的内容. 做的是jQuery框架的隐藏和显示,HTML如下: <ul> <li>1</li> <li>2</l ...

  4. SQL Server 中创建数据库、更改主文件组示例

    以下示例在 SQL Server 实例上创建了一个数据库.该数据库包括一个主数据文件.一个用户定义文件组和一个日志文件.主数据文件在主文件组中,而用户定义文件组包含两个次要数据文件.ALTER DAT ...

  5. 使用idea将本地项目上传至github及clone

    一.上传 1.firl->settings 设置git 2.firl->settings 填写自己的登录名和密码,可以使用test测试是否连接成功 3. 就搞定了.github会自动建立一 ...

  6. SVN 密码破解,svn密码本地找回 忘记密码

    svn 密码被保存在本地文件中 C:\Users\[your computer name]\AppData\Roaming\Subversion\auth\svn.simple 文件下. 加密保存 到 ...

  7. iOS_SN_CoreDate(一)封装使用

    看过一篇封装CoreData的文章挺不错,有基本使用封装,但是没有写怎么与tableView结合使用,我自己用的过程有些小波折,自己做了一个demo,大家可以看源码一些基本使用应该不难了, 原文:ht ...

  8. jQuery自学笔记(五):关于jQuery的遍历

    向上遍历 DOM 树 parent()  //返回被选元素的直接父元素,该方法只会向上一级对 DOM 树进行遍历. parents()    //返回被选元素的所有祖先元素,它一路向上直到文档的根元素 ...

  9. 3月19日 html(一) html基础内容

    ---恢复内容开始--- 今天学习了html的第一节课,是些比较简单的基础知识,知道如何向网页里添加文本.图片.表格.超链接之类的,如何去编写这些代码. html(hyper text makeup ...

  10. C语言基础学习基本数据类型-其他整数类型

    其他整数类型 初学C语言时,int类型会满足你对整数的大多数需求. C语言还提供了三个关键字用以修饰基本的整数类型:short.long和unsigned.有以下几个注意点: (1)C语言没有具体规定 ...