AsyncTask kill task when back button pressed
I am having a little problems with AsyncTask.
I have it implemented as follows
private class MakeConnection extends AsyncTask<String, Void, String> implements OnDismissListener{
Context context;
ProgressDialog myDialog;
public MakeConnection(Context conetext)
{
this.context = conetext;
myDialog = new ProgressDialog(this.context);
myDialog.setCancelable(true);
开发者_开发技巧 myDialog.setOnDismissListener(this);
}
@Override
protected String doInBackground(String... urls) {
//do stuff
}
@Override
protected void onPostExecute(String result) {
try {
myDialog.dismiss();
success(result);
}catch(JSONException e)
{
data = e.toString();
}
}
@Override
protected void onProgressUpdate(Void... values) {
myDialog = ProgressDialog.show(context, "Please wait...", "Loading the data", true);
}
@Override
public void onDismiss(DialogInterface dialog) {
this.cancel(true);
}
}
But when ever I press the back button nothing happens, it just completes the task as if I didn't press the back button
Any idea why?
There are two parts of this problem:
1) Implement your doInBackground()
in such a way, so it checks whether AsyncTask
is cancelled.
@Override
protected String doInBackground(String... urls) {
for(int i = 0; i < 100 && !isCancelled(); i++) {
//do some stuff
}
}
2) You should call asynTask.cancel(true)
in your Activity's onDestroy()
.
This fixes my problem
@Override
protected void onPreExecute(){
myDialog = ProgressDialog.show(
context,
"Please wait...",
"Loading the data",
true,
true,
new DialogInterface.OnCancelListener(){
@Override
public void onCancel(DialogInterface dialog) {
MakeConnection.this.cancel(true);
}
}
);
}
it is also possible to use follwing method in activity
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
imageLoadingAsyncTask.cancel(true);
}
精彩评论