I need to cancel my AsyncTask with a button in the progress dialog.
I've created the Progress dialog with the button. Here it is:
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(DSDactivity.this);
pDialog.setMessage(getResources().getString(R.string.pDialog));
pDialog.setCancelable(false);
pDialog.setButton("Cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
pDialog.dismiss();
asyncCodelist.cancel(true);
}
});
pDialog.show();
}
I have two problems:
When I click "cancel" on the progress dialog is removed but the async task continues to do what he was doing
Eclipse gives me this waning:
The method setButton(CharSequence, DialogInterface.OnClickListener) from the type AlertDialog is deprecated
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(DSDactivity.this);
pDialog.setMessage(getResources().getString(R.string.pDialog));
pDialog.setCancelable(true);
pDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
myTask.cancel(true);
dialog.dismiss();
}
}
}
And then, as my link said, create your AsyncTask and store it :
MyAsyncTask myTask=null;
and execute it like this :
myTask = new MyAsyncTask();
myTask.execute();
myTask.cancel(true);
As the document states:
To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)
setButton()
method is deprecated now for ProgressDialog
, hence the warning. It will definitely work though.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.