解决如何让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();
    }
}

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索android
, sql server与android
, network error
, android so...
, private
, this
, toast
, doinbackground
, asynctask
, import
, finish
, progressdialog
, cancel
org.apache.http
asynctask终止、终止ftp会话怎么解决、终止批处理操作吗、已终止操作、无法打开 已终止操作,以便于您获取更多的相关知识。

时间: 2024-09-17 04:52:10

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

Win7系统使用IE浏览器弹出“无法打开internet站点 已终止操作”的解决方法

  windows操作系统内置有IE浏览器,也是我们使用的最多次的浏览器之一了,但有时win7纯净版系统在使用IE浏览器过程中,也会遇到各种问题.比如最近我们打开网页时,会弹出一个提示框"Internet Explorer无法打开Internet 站点about:blank.已终止操作",遇到这样问题该如何解决呢?带着此问题,下面小编和大家分享具体的解决方法. 方法如下: 一.重置IE 方法原理:重置IE,把篡改的错误设置全部清除,恢复干净的IE设置. 注意事项:重置IE后,里面的有部

无法打开internet站点已终止操作解决方法4则

  大家在上网时有没有遇到这样的情况:打开某个网页时,系统弹出"无法打开internet站点已终止操作"这个错误提示,遇到这种情况该怎么解决呢?下文有4种解决方法,希望对大家有帮助. 法一.重置IE 方法原理:重置IE,把篡改的错误设置全部清除,恢复干净的IE设置. 注意事项:重置IE后,里面的有部分插件或者控件失效,需要重装. 操作步骤: 1.首先打开IE浏览器,选择菜单栏的"工具",选中"internet选项"; 2.在"inter

IE6已终止操作问题的2种情况及解决_javascript技巧

令人崩溃的IE6问题再次出现,打开某个页面时,弹出提示框"Internet Explorer无法打开Internet 站点...已终止操作". 查了一下资料,感觉"因为js(一个比较复杂的js)写在body里面,在body元素加载完之前调用出现问题"的说法比较靠谱. 经过一番奋战,利用排除法解决了问题,共发现2种情况. ①原因:同一JS文件,先后引入2次. 解决:删除一个即可. ②原因:在body里直接调用JS文件中的方法. 解决:通过onload或jquery.r

“internet explore 无法打开internet站点 已终止操作”的解决方法_应用技巧

这是因为: 在IE下,在加载文档的过程中,整个HTML文档的DOM结构尚未生成完整,而此时正在执行的JS就已创建出新的DOM结点了,致使DOM树的结构发生紊乱. 易出错写法: 复制代码 代码如下: <html>  <head>  <title> xxxxxxxxxxxx </title>  <meta http-equiv="content-type" content="text/html; charset=utf-8&q

IE无法打开internet站点已终止操作 求解 大牛们快来接分

问题描述 IE无法打开internet站点已终止操作的解决办法总是这样比如我编辑或者添加或者删除时操作后就弹出"IE无法打开internet站点已终止操作"但是最终的操作时完成了的在我的电脑上可以环境的IE7客户那边也是IE7就不行了在google下又可以求解求解说JS加载问题吧!在是同为IE7自己机器上可以客户那不行google下也可以求解求解 解决方案 解决方案二:一.检查自己的网页代码中是否有没有闭合的HTML标签.如果代码太多,建议使用一些在线代码验证检测工具去完成这项任务.二

解决win7系统无法进入操作中心的方法教程

  Windows操作中心是一个查看警报和执行操作的中心位置,它可帮助保持 Windows 稳定运行,不过在win7系统下,windows操作中心貌似很少用户会进入查看,不过不能因为我们不经常使用而对其不理不睬,近期有部分使用win7系统的用户向小编反映,在即的windows操作中心无法打开,对于出现该问题的用户我们应该如何解决呢?下面看小编为大家带来的解决方法! 解决win7系统无法进入操作中心的方法教程 1.首先,我们同时按下win7电脑键盘上的win+R快捷键打开电脑的运行窗口,在打开的运

JSP页面IE无法打开Internet 站点…… 已终止操作 的解决方法_JSP编程

之所以说机缘巧合,意思是各种因素促成了这个事件,缺一不可.几个因素分别是:系统中的ie是ie6(具体的小版本之间的差别我不是很确定or清楚).编写jsp页面且用开发工具自动生成的jsp源码.使用了WdatePicker.js这个时间控件.以及页面代码的一些书写顺序. 之所以说经典,很明显,从上面的巧合中可以看出来了,ie6绝对是经典了. 全部测试代码如下(除要引用的控件相关文件外) 复制代码 代码如下: <%@ page language="java" import="

IE6弹出“已终止操作”的解决办法_javascript技巧

在实际的项目中,我的这个js是在头部页面里面,头部被多个页面引用,如果在每个页面的body元素里面加<body onload="函数">,可以解决问题,但是这样做太不符合实际了.毕竟全改的话,到时候布署到外网,要更新太多的文件.于是,在网上找了一下,让这段js最后执行的代码,终于让我找到了.代码如下: 复制代码 代码如下: <scirpt type="text/javascript"> document.onreadystatechange

详解Java多线程编程中线程的启动、中断或终止操作_java

线程启动: 1.start() 和 run()的区别说明start() : 它的作用是启动一个新线程,新线程会执行相应的run()方法.start()不能被重复调用. run() : run()就和普通的成员方法一样,可以被重复调用.单独调用run()的话,会在当前线程中执行run(),而并不会启动新线程! 下面以代码来进行说明. class MyThread extends Thread{ public void run(){ ... } }; MyThread mythread = new