解决如何让AsyncTask终止操作
受到这个的启发终于结局了如何在AsyncTask运行中终止其操作。
单纯的onCancelled(true)是不行的
下面把代码贴出来~实现了登陆功能。
AsyncTask简介,它使创建需要与用户界面交互的长时间运行的任务变得更简单。相对来说AsyncTask更轻量级一些,适用于简单的异步处理,不需要借助线程和Handler即可实现。
- 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终止操作的更多相关文章
- IE无法打开internet网站已终止操作的解决的方法
用IE内核浏览器的朋友,或许不经意间会碰到这样滴问题: 打开某个网页时,浏览器“嘣”跳出一个提示框“Internet Explorer无法打开Internet 站点...已终止操作”.而大多数情况下该 ...
- 解决IE6已终止操作问题
令人崩溃的IE6问题再次出现,打开某个页面时,弹出提示框“Internet Explorer无法打开Internet 站点...已终止操作”. 查了一下资料,感觉“因为js(一个比较复杂的js) ...
- IE6“无法打开站点,已终止操作”提示的解决
今天遇到一个问题,网站在IE 6下面打开会提示:Internet Explorer无法打开站点XXX.已终止操作. 先介绍一下网上常见的解决方法. 因为在页面还没有ready的时候就调用了htmlOb ...
- 关于日历控件My97DatePicker 在IE6下出现“无法打开站点,已终止操作”
1.My97DatePicker 官方:http://www.my97.net2.在IE6下出现“无法打开站点,已终止操作”的解决办法(转): .这是一个绝对有效的方法,但是会丢失跨越iframe的特 ...
- 使用<base target="_self" /> IE6 cann't open the Internet site 已终止操作
今日发现一个问题,我的网页需要用到<base target="_self" />,经测试IE8,9 谷歌 火狐全都正常,但是IE6 showModalDialog ...
- ie6 无法显示网页 已终止操作
已终止操作原因: 在文件加载完成之前执行了dom操作,如appendChild, innerHTML等 解决办法: ready后再执行
- java8-10-Stream的终止操作
Stream的终止操作 * allMatch 是否匹配所有 * anyMatch 是否匹配一个 * noneMatch 是否没有匹配一个 * findFirst 返回第一个 * count ...
- jm解决乱码问题-参数化-数据库操作-文件上传下载
jm解决乱码问题-参数化-数据库操作-文件上传下载 如果JM出果运行结果是乱码(解决中文BODY乱码的问题) 找到JM的安装路径,例如:C:\apache-jmeter-3.1\bin 用UE打开jm ...
- m_Orchestrate learning system---十、解决bug最根本的操作是什么
m_Orchestrate learning system---十.解决bug最根本的操作是什么 一.总结 一句话总结:多学多练,遇到bug超级轻松 1.如何查看js代码的异常? 开发者选项里面可以查 ...
随机推荐
- 深入浅出 RPC - 浅出篇
近几年的项目中,服务化和微服务化渐渐成为中大型分布式系统架构的主流方式,而 RPC 在其中扮演着关键的作用.在平时的日常开发中我们都在隐式或显式的使用 RPC,一些刚入行的程序员会感觉 RPC 比较神 ...
- Word03-文档中的截图显示不全
今天写文档时遇到个很蛋疼的问题,在doc文档中复制进去的截图总是显示不全,图片上半部分都被文字遮盖了,折腾半天,最后还是网上找到了答案. 解决方法如下: 将图片所在行的段落行距修改为其它值即可,原来为 ...
- 解决操作过快导致ajax异常的办法
//控制点击过快ajax异常 var state = true; function test() { if (state) { state = false; var val = accMul((uCo ...
- (转)WITH (NOLOCK)
缺点: 1.会产生脏读 2.只适用与select查询语句 优点: 1.有些文件说,加了WITH (NOLOCK)的SQL查询效率可以增加33%. 2.可以用于inner join 语句 脏读: 一个用 ...
- JavaScript和ajax 跨域的案例
今天突然想看下JavaScript和ajax 跨域问题,然后百度看了一下,写一个demo出来 <!DOCTYPE html> <html xmlns="http://www ...
- 高性能ORM框架XLinq功能详细介绍
之前简单介绍了XLinq的一些功能,有很多功能都没有提到,现在给XLinq加了一些功能,这次把所有功能都介绍一遍. 设计目标 易用性 在使用一个框架的时候 应该没几个人会喜欢写一大堆的配置文件吧 也应 ...
- uva 10894 - Save Hridoy
#include <iostream> #include <string> #include <cstring> #include <cmath> us ...
- PHP扩展开发(2) - VS2013环境搭建
1. 安装VS2013 2. Cygwin安装 3. 下载Windows的PHP源码 4. 修改~/ext/ext_skel_win32.php 加上 $cygwin_path = 'c:\c ...
- QT打开网页 QURL
用QT打开一个网页就是先定义一个QUrl对象url,然后利用QDesktopServices::open(url)即可. 例如: const QUrl url(http://www.baidu.com ...
- android开发3:四大基本组件的介绍与生命周期
android开发3:四大基本组件的介绍与生命周期 Android四大基本组件分别是Activity,Service服务,Content Provider内容提供者,BroadcastReceiver ...