Inspired by this, it finally ends. How to terminate an operation in a asynctask run.
Pure oncancelled (true) is not possible.
The following code posted out ~ to achieve the landing function.
Asynctask introduction, which makes it easier to create long-running tasks that require interaction with the user interface. Asynctask is relatively lightweight, suitable for simple asynchronous processing, and does not require the help of threads and 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 PA
ssWOrd ", Toast.length_short). Show ();
else {//show dialog by passing ID ShowDialog (progressdialog_id);
}
}
}); } protected Dialog oncreatedialog (int id) {switch (ID) {Case progressdialog_id:removed
Ialog (progressdialog_id);
Please note that forth parameter be true for cancelable Dialog//also Register Cancel event Listener If the Litener is registered then forth parameter has no effect ProgressDialog = Progressdialog.show (Us
Erlogin.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 being only cancelled if It isn't in finished stat
E 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 PROGRESSD IALOG_ID://check If any previous the task is running, if so then cancel it//it can be cancelled if I T is not in finished state if (logintask!= null && logintask.getstatus ()!=
) Logintask.cancel (TRUE); Logintask = new Logintask ();
Every time create new object, as Asyntask'll is executed one time. LogiNtask.execute (); Class Logintask extends Asynctask<void, Integer, void> {@Override protected Void doin Background (Void ... unused) {try {serverresponse = null;//don ' t forget to make it null, as T
Ask 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 your make server call//calling on this statement and canceling task'll n o meaning if you some update database kind of operation//so is wise to choose correct place to put thi
S condition//you can also put this condition in as loop, if you are doing task Now this is very important//if you don't put this condition and not maintaining execution, then there is no meaning of calling. Cancel () method//you should only check this condition in Doinbackground () metho D, otherwise there is no logical meaning if (iscancelled ()) {publishp Rogress (cancelled); Notify your activity, you had canceled the task return (null); Don ' t forget to terminate this methOD} httpresponse response = Httpclient.execute (HttpGet, Localcont
EXT);
BufferedReader reader = new BufferedReader (New InputStreamReader (
Response.getentity (). GetContent (), "UTF-8"));
Serverresponse = Reader.readline (); Publishprogress (SUCCESS); If everything is Okay then publish this message, your may also use OnPostExecute () method} catch (Unknownhos
Texception 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 (serv
Erresponse); String smessage = Jresponse.getstrinG ("message");
int success = Jresponse.getint ("Success"); if (success = = 1) {//proceed Further//you may start new Activi Ty from-here-//after, want to finish the activity use
RLogin.this.finish (); Remember when you finish a activity, it doesn ' t mean so you also finish thread or Asyntask started within that Activi
Ty//so You must implement OnDestroy () method and terminate those.
else {//just showing invalid username password from server response Toast.maketext (Getapplicationcontext (), smessage, Toast.length_short). Show (
); The 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 isn't handled in Doinbackground () method if (logintask!= null && logintask.getstatus ()!= AsyncTask.Status.FINISHED) Logintask.cancel
(true);
Super.ondestroy (); }
}