I would like to cancel an Asynctask
in android but I have a problem with my implementation :
My code is :
private class SynchroTask extends AsyncTask{
private volatile boolean running = true;
@Override
protected void onPreExecute() {
super.onPreExecute();
//INITIALIZATIONS
}
@Override
protected Void doInBackground(Void... params) {
while (running) {
//TASK
}
return null;
}
@Override
protected void onCancelled(){
super.onCancelled();
running = false;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Intent intent = AccountAddActivity.getIntent(getActivity());
startActivity(intent);
getActivity().finish();
}
}
}
And :
mSynchroTask = new SynchroTask();
cancelButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if (mSynchroTask != null && mSynchroTask.getStatus() != AsyncTask.Status.FINISHED){
HDCApplication.hdcAppManager.mSynchroManager.removeAllTask();
mSynchroTask.cancel(true);
mSynchroTask = null;
}
}
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…