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

单纯的onCancelled(true)是不行的

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

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

转自stackoverflow

  1. package com.isummation.exampleapp;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.InputStreamReader;
  5. import java.net.URLEncoder;
  6. import java.net.UnknownHostException;
  7.  
  8. import org.apache.http.HttpResponse;
  9. import org.apache.http.client.HttpClient;
  10. import org.apache.http.client.methods.HttpGet;
  11. import org.apache.http.impl.client.DefaultHttpClient;
  12. import org.apache.http.params.CoreProtocolPNames;
  13. import org.apache.http.protocol.BasicHttpContext;
  14. import org.apache.http.protocol.HttpContext;
  15. import org.json.JSONObject;
  16.  
  17. import android.app.Activity;
  18. import android.app.Dialog;
  19. import android.app.ProgressDialog;
  20. import android.content.DialogInterface;
  21. import android.content.DialogInterface.OnCancelListener;
  22. import android.os.AsyncTask;
  23. import android.os.Bundle;
  24. import android.view.View;
  25. import android.view.View.OnClickListener;
  26. import android.widget.Button;
  27. import android.widget.EditText;
  28. import android.widget.Toast;
  29.  
  30. public class UserLogin extends Activity {
  31.  
  32. private EditText etUsername;
  33. private EditText etPassword;
  34. private ProgressDialog progressDialog;
  35. private static final int PROGRESSDIALOG_ID = 0;
  36. private static final int SERVER_ERROR = 1;
  37. private static final int NETWORK_ERROR = 2;
  38. private static final int CANCELLED = 3;
  39. private static final int SUCCESS = 4;
  40. private String ServerResponse;
  41. private LoginTask loginTask;
  42.  
  43. @Override
  44. public void onCreate(Bundle savedInstanceState) {
  45. super.onCreate(savedInstanceState);
  46. setContentView(R.layout.login);
  47.  
  48. etUsername = (EditText) findViewById(R.id.txt_username);
  49. etPassword = (EditText) findViewById(R.id.txt_password);
  50.  
  51. Button login_button = (Button) this.findViewById(R.id.login_button);
  52. login_button.setOnClickListener(new OnClickListener() {
  53. public void onClick(View viewParam) {
  54. if (etUsername.getText().toString().length() == 0
  55. || etPassword.getText().toString().length() == 0) {
  56. Toast.makeText(getApplicationContext(),
  57. "Please enter username and password",
  58. Toast.LENGTH_SHORT).show();
  59. } else {
  60.  
  61. //Show dialog by passing id
  62. showDialog(PROGRESSDIALOG_ID);
  63. }
  64. }
  65. });
  66. }
  67.  
  68. protected Dialog onCreateDialog(int id) {
  69. switch(id) {
  70. case PROGRESSDIALOG_ID:
  71. removeDialog(PROGRESSDIALOG_ID);
  72.  
  73. //Please note that forth parameter is true for cancelable Dialog
  74. //Also register cancel event listener
  75. //if the litener is registered then forth parameter has no effect
  76. progressDialog = ProgressDialog.show(UserLogin.this, "Authenticating",
  77. "Please wait...", true, true, new OnCancelListener(){
  78.  
  79. public void onCancel(DialogInterface dialog) {
  80. //Check the status, status can be RUNNING, FINISHED and PENDING
  81. //It can be only cancelled if it is not in FINISHED state
  82. if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
  83. loginTask.cancel(true);
  84. }
  85. });
  86. break;
  87. default:
  88. progressDialog = null;
  89. }
  90. return progressDialog;
  91. }
  92.  
  93. @Override
  94. protected void onPrepareDialog(int id, Dialog dialog) {
  95. switch (id) {
  96. case PROGRESSDIALOG_ID:
  97. //check if any previous task is running, if so then cancel it
  98. //it can be cancelled if it is not in FINISHED state
  99. if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
  100. loginTask.cancel(true);
  101. loginTask = new LoginTask(); //every time create new object, as AsynTask will only be executed one time.
  102. loginTask.execute();
  103. }
  104. }
  105.  
  106. class LoginTask extends AsyncTask<Void, Integer, Void> {
  107. @Override
  108. protected Void doInBackground(Void... unused) {
  109. try {
  110. ServerResponse = null; //don't forget to make it null, as task can be called again
  111. HttpClient httpClient = new DefaultHttpClient();
  112. HttpContext localContext = new BasicHttpContext();
  113. HttpGet httpGet = new HttpGet(
  114. getString(R.string.WebServiceURL)
  115. + "/cfc/iphonewebservice.cfc?returnformat=json&method=validateUserLogin&username="
  116. + URLEncoder.encode(etUsername.getText()
  117. .toString(), "UTF-8")
  118. + "&password="
  119. + URLEncoder.encode(etPassword.getText()
  120. .toString(), "UTF-8"));
  121. httpClient.getParams().setParameter(
  122. CoreProtocolPNames.USER_AGENT,"Some user agent string");
  123.  
  124. //call it just before you make server call
  125. //calling after this statement and canceling task will no meaning if you do some update database kind of operation
  126. //so be wise to choose correct place to put this condition
  127. //you can also put this condition in for loop, if you are doing iterative task
  128.  
  129. //now this very important
  130. //if you do not put this condition and not maintaining execution, then there is no meaning of calling .cancel() method
  131. //you should only check this condition in doInBackground() method, otherwise there is no logical meaning
  132. if (isCancelled())
  133. {
  134. publishProgress(CANCELLED); //Notify your activity that you had canceled the task
  135. return (null); // don't forget to terminate this method
  136. }
  137. HttpResponse response = httpClient.execute(httpGet,
  138. localContext);
  139.  
  140. BufferedReader reader = new BufferedReader(
  141. new InputStreamReader(
  142. response.getEntity().getContent(), "UTF-8"));
  143. ServerResponse = reader.readLine();
  144. publishProgress(SUCCESS); //if everything is Okay then publish this message, you may also use onPostExecute() method
  145. } catch (UnknownHostException e) {
  146. removeDialog(PROGRESSDIALOG_ID);
  147. e.printStackTrace();
  148. publishProgress(NETWORK_ERROR);
  149. } catch (Exception e) {
  150. removeDialog(PROGRESSDIALOG_ID);
  151. e.printStackTrace();
  152. publishProgress(SERVER_ERROR);
  153. }
  154. return (null);
  155. }
  156.  
  157. @Override
  158. protected void onProgressUpdate(Integer... errorCode) {
  159. switch (errorCode[0]) {
  160. case CANCELLED:
  161. removeDialog(PROGRESSDIALOG_ID);
  162. Toast.makeText(getApplicationContext(), "Cancelled by user",
  163. Toast.LENGTH_LONG).show();
  164. break;
  165. case NETWORK_ERROR:
  166. removeDialog(PROGRESSDIALOG_ID);
  167. Toast.makeText(getApplicationContext(), "Network connection error",
  168. Toast.LENGTH_LONG).show();
  169. break;
  170. case SERVER_ERROR:
  171. removeDialog(PROGRESSDIALOG_ID);
  172. Toast.makeText(getApplicationContext(), "Server error",
  173. Toast.LENGTH_LONG).show();
  174. break;
  175. case SUCCESS:
  176. removeDialog(PROGRESSDIALOG_ID);
  177. try {
  178. if (ServerResponse != null) {
  179. JSONObject JResponse = new JSONObject(ServerResponse);
  180. String sMessage = JResponse.getString("MESSAGE");
  181. int success = JResponse.getInt("SUCCESS");
  182. if (success == 1) {
  183. //proceed further
  184.  
  185. //you may start new activity from here
  186. //after that you may want to finish this activity
  187. UserLogin.this.finish();
  188.  
  189. //Remember when you finish an activity, it doesn't mean that you also finish thread or AsynTask started within that activity
  190. //So you must implement onDestroy() method and terminate those threads.
  191. } else {
  192. //just showing invalid username password from server response
  193. Toast.makeText(getApplicationContext(), sMessage,
  194. Toast.LENGTH_SHORT).show();
  195. }
  196. }
  197. } catch (Exception e){
  198. Toast.makeText(getApplicationContext(), "Server error",
  199. Toast.LENGTH_LONG).show();
  200. e.printStackTrace();
  201. }
  202. break;
  203. }
  204. }
  205.  
  206. @Override
  207. protected void onPostExecute(Void unused) {
  208.  
  209. }
  210. }
  211.  
  212. @Override
  213. protected void onDestroy(){
  214. //you may call the cancel() method but if it is not handled in doInBackground() method
  215. if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
  216. loginTask.cancel(true);
  217. super.onDestroy();
  218. }
  219. }

原文出处: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. 深入浅出 RPC - 浅出篇

    近几年的项目中,服务化和微服务化渐渐成为中大型分布式系统架构的主流方式,而 RPC 在其中扮演着关键的作用.在平时的日常开发中我们都在隐式或显式的使用 RPC,一些刚入行的程序员会感觉 RPC 比较神 ...

  2. Word03-文档中的截图显示不全

    今天写文档时遇到个很蛋疼的问题,在doc文档中复制进去的截图总是显示不全,图片上半部分都被文字遮盖了,折腾半天,最后还是网上找到了答案. 解决方法如下: 将图片所在行的段落行距修改为其它值即可,原来为 ...

  3. 解决操作过快导致ajax异常的办法

    //控制点击过快ajax异常 var state = true; function test() { if (state) { state = false; var val = accMul((uCo ...

  4. (转)WITH (NOLOCK)

    缺点: 1.会产生脏读 2.只适用与select查询语句 优点: 1.有些文件说,加了WITH (NOLOCK)的SQL查询效率可以增加33%. 2.可以用于inner join 语句 脏读: 一个用 ...

  5. JavaScript和ajax 跨域的案例

    今天突然想看下JavaScript和ajax 跨域问题,然后百度看了一下,写一个demo出来 <!DOCTYPE html> <html xmlns="http://www ...

  6. 高性能ORM框架XLinq功能详细介绍

    之前简单介绍了XLinq的一些功能,有很多功能都没有提到,现在给XLinq加了一些功能,这次把所有功能都介绍一遍. 设计目标 易用性 在使用一个框架的时候 应该没几个人会喜欢写一大堆的配置文件吧 也应 ...

  7. uva 10894 - Save Hridoy

    #include <iostream> #include <string> #include <cstring> #include <cmath> us ...

  8. PHP扩展开发(2) - VS2013环境搭建

    1. 安装VS2013 2. Cygwin安装 3. 下载Windows的PHP源码 4. 修改~/ext/ext_skel_win32.php     加上 $cygwin_path = 'c:\c ...

  9. QT打开网页 QURL

    用QT打开一个网页就是先定义一个QUrl对象url,然后利用QDesktopServices::open(url)即可. 例如: const QUrl url(http://www.baidu.com ...

  10. android开发3:四大基本组件的介绍与生命周期

    android开发3:四大基本组件的介绍与生命周期 Android四大基本组件分别是Activity,Service服务,Content Provider内容提供者,BroadcastReceiver ...