解决如何让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代码的异常? 开发者选项里面可以查 ...
随机推荐
- ado.net 数据库连接的两方式种
DataAdapter: string connectionString = "data source=127.0.0.1;Database=dong;user id=sa;password ...
- CSS Hack是什么意思
CSS hack由于不同的浏览器,比如Internet Explorer 6,Internet Explorer 7,Mozilla Firefox等,对CSS的解析认识不一样,因此会导致生成的页面效 ...
- css如何实现背景透明,文字不透明?
之前做了个半透明弹层,但设置背景半透明时,子元素包含的字体及其它元素也都变成了半透明.对opacity这个属性认识的不透彻,在这里做一些总结,方便以后使用. 背景透明,文字不透明的解决方法: ...
- (转)chm格式的电子书打开是空白的解决办法
当我们从网络上下载chm格式的电子书到本地后,打开就发现chm格式的电子书右边的目录是正常的,但是chm格式的电子书内容部分却是空白的情况,很多时候我们都以为是中毒了,但是用杀毒软件却杀不出来,其实很 ...
- Android --------- 命名规范
工程 软件名称,最好是英文首字母大写:如MobileSafe. 包 企业单位网址的倒序+软件名称:如com.baidu.mobilesafe. 类 类中分为:(头字母小写,其他每个单子首字母大写) 1 ...
- 查询矩形范围内的"点"要素
步骤 1,首先在含有主视图控件 ESRI.ArcGIS.Controls.AxMapControl mapCtrl_main 的主类中定义一个 IEnvelope 成员变量,用于记录鼠标在主视图控件画 ...
- 解析c语言背后的汇编代码
源码 很简单的c语言代码,作用是交换两个数: #include <stdio.h> void swap(int * a, int * b) { *a = *a + *b - (*b = * ...
- Swift 字符串连接
// 使用+直接相加 var i = var str = "Hello" str = str + " jinpangpang" // 可以使用这种方式连接整值 ...
- JS/CSS/IMG加载顺序关系之DOMContentLoaded事件
DOMContentLoaded介绍 DOMContentLoaded事件的触发条件是: 将会在“所有的DOM全部加载完毕并且JS加载执行后触发”. 但如果“js是通过动态加载进来的话,是不会影响到D ...
- js的一个稍微高级点的用法
通过问题来说明: 1.一个系统中,要创造很多对象,为每个对象分配一个唯一的ID 1: var createObj = (function(){ 2: var i = 0; 3: return func ...