Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop async task executions when back button is pressed

Please i have an activity that contains async task method, This async task method continues to execute in background even when the user has moved from that page. Please is there a way to stop async task executions as soon as a user press on the back button or move from that page to another page.

Below is what i have tried but it isnt working

private AsyncTask totalLikesAsync;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);
    context = this;

   totalLikesAsync = new TotalLikes().execute(msgID);
}






@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
    switch (menuItem.getItemId()) {
        case android.R.id.home:

            totalLikesAsync.cancel(true);
            this.finish();
            break;

        case R.id.share:
            new ShareImage().execute(msgImage);
        default:
            return super.onOptionsItemSelected(menuItem);
    }
    return true;
}





private class TotalLikes extends AsyncTask<String, String, JSONObject> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }



    @Override
    protected JSONObject doInBackground(String... msgIDs) {
        UserFunctions userFunction = new UserFunctions();

        String msgsID = msgIDs[0];
        JSONObject json=null;

        if(!isCancelled()){

            //This gets all the information unread from the server
            json = userFunction.TotalLikes(context, msgsID);
        }

        return json;
    }

    @Override
    protected void onPostExecute(JSONObject json) {
        /**
         * Checks for success message.
         **/
        if (json != null) {

            ...
        } else {

           ...
        }

}
}

UPDATE

After testing all the answers below, they all allow the execution of doinbackground within the async task even though the back button is pressed. I want a situation where the Background would be cancelled as soon as back button is pressed.

like image 426
NewBIe Avatar asked Dec 01 '25 06:12

NewBIe


1 Answers

@Override
public void onBackPressed() {
    super.onBackPressed();
    if (totalLikesAsync != null && totalLikesAsync.getStatus().equals(AsyncTask.Status.RUNNING)) {
        totalLikesAsync.cancel(true);
    }
} 
like image 85
Beena Avatar answered Dec 02 '25 21:12

Beena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!