First Lets have a class like LoginTask
class
LoginTask
extends
AsyncTask<String, Void, String> {
private
LoginTask loginTask;
@Override
protected
Void doInBackground(String... unused) {
if
(isCancelled())
{
//
retun from here
return
null
;
}
// Do your task you want just add this line
}
@Override
protected
void
onPostExecute(String result) {
}
}
// Here let say Your main Activity from where you want to cancel your lask
public
class
LoginActivity
extends
Activity {
@Override
public
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Start login task here ok
loginTask =
new
LoginTask();
loginTask.execute();
}
//Cancell task here
public void cancelTask(){
//Just check the condition like its Running,Finished or Pending
//import Status as like AsynkTask.Status and cancel the task if it is running than it will call cancel and //you will return to post execute with null value
if
(loginTask !=
null
&& loginTask.getStatus() != Status.FINISHED)
loginTask.cancel(
true
);
}
@Override
onBackPressed(){// Let say you want to cancel task on back press
cancelTask();
}
}
No comments:
Post a Comment