Stop AsyncTask in Fragments when Back Button is pressed

前端 未结 5 1551
别跟我提以往
别跟我提以往 2021-01-17 01:17

i have an activities that host fragments. pressing a button goes from fragment A to fragment B through a FragmentTransaction and the added to the back stack. Now fragment B

5条回答
  •  悲哀的现实
    2021-01-17 01:47

    Just call this code in the onBackPressed()-method of your hosting Activity - same applies to a Fragment via onDestroy():

    if(myFancyAsyncTask != null && myFancyAsyncTask.getStatus() == Status.RUNNING) {
      myFancyAsyncTask.cancel(true);
    }
    

    This will cancel a running AsyncTask for you. Be sure to check back in the AsyncTask if it was not cancelled by using the lifecycle-methods:

    protected void onPostExecute(Long result) {
         if(!isCancelled()) {
           // do your work
         }
     }
    

提交回复
热议问题