0
I have the following asynctask, which contains an Handler inside it, but when I leave Activity I close the async but sometimes Handler keeps calling the async after it’s closed. No crash in the application but keeps sending logs as if it was giving error, follows below async
public class PostImageAsyncTask extends AsyncTask<Object, Object, PutObjectResult> {
public PostImageAsyncTask() {
super();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// before making http calls
}
@Override
protected PutObjectResult doInBackground(Object... params) {
try {
return amazonS3Client.putObject(por);
} catch (AmazonServiceException e) {
return null;
} catch (AmazonClientException e) {
return null;
}
}
@Override
protected void onPostExecute(PutObjectResult result) {
if (!isCancelled()) {
if (result != null) {
showAndHideLoad(false);
if(step == 0) {
picture = new Picture(amazonUrl, null);
} else if(step == 1) {
documentIDs = new DocumentIDs(amazonUrl,null);
} else if( step == 2){
documentIDs.setBackURL(amazonUrl);
}
if ((snackbar != null && snackbar.isShown())) {
snackbar.dismiss();
}
send_continue();
} else {
if (RECONECT_TIME_DELAY < MAX_TIME_DELAY) {
if ((snackbar == null || !snackbar.isShown())) {
isClicked=false;
snackbar = Snackbar.make(coordinatorLayoutView, getString(R.string.snackbar_internet_fail), Snackbar.LENGTH_INDEFINITE);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
snackbar.setActionTextColor(Color.RED);
snackbar.setAction("Cancelar", new View.OnClickListener() {
@Override
public void onClick(View view) {
//
}
});
snackbar.show();
}
handler.postDelayed(new Runnable() {
@Override
public void run() {
RECONECT_TIME_DELAY = RECONECT_TIME_DELAY * 2;
postImageAsyncTask.cancel(true);
postImageAsyncTask = new PostImageAsyncTask();
postImageAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}, RECONECT_TIME_DELAY);
}
}
} else {
postImageAsyncTask.cancel(true);
}
}
}
Asynctasks are not meant to match Handler. You should make the various connection attempts at doInBackground() and each failed attempt call publishProgress(), which makes onProgressUpdate() to be called (in it you can update the screen elements).
– Piovezan