Stop AsyncTask in Fragments when Back Button is pressed

前端 未结 5 1506
别跟我提以往
别跟我提以往 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:41
        AsyncTaskRunner doAsynchronousTask; //Before onCreateView
    
    //in onCreateView() 
        doAsynchronousTask = new AsyncTaskRunner();``
        doAsynchronousTask.execute();
    
    
    // after  onCreateView()
        @Override
        public void onStop() {
            super.onStop();
            doAsynchronousTask.cancel(true);
        }
    
    0 讨论(0)
  • 2021-01-17 01:43

    Override the onStop() of your fragment and do:

    protected void onStop() {
        super.onStop();
    
        //check the state of the task
        if(task != null && task.getStatus() == Status.RUNNING)
            task.cancel(true);
    }
    
    0 讨论(0)
  • 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
         }
     }
    
    0 讨论(0)
  • 2021-01-17 01:50

    Canceling the AsyncTask in onStop() is not a very good choice because it can stop the AsyncTask in scenarios where you would want it to keep running. Imagine you have a fragment/activity where you show several images downloaded from the net and tapping an image is supposed to take the user to another image specific app. This would make your fragment hit onStop() and cancel your AsyncTask even though there may still be images you want to download for when the user comes back to the activity. I think doing it in onDestroy() is a better choice.

    @Override
    public void onDestroy() {
        super.onDestroy();
    
        if(doTask != null){
            doTask.cancel(true);
        }
    }
    
    0 讨论(0)
  • 2021-01-17 01:59

    I strongly recommend you to see this life cycle of fragment to avoid future confusions. And In your case I think you should override onPause method to top the asyncTask.

     @Override
    protected void onPause() {
        super.onPause();
         //check the state of the task
        if(task != null && task.getStatus() == Status.RUNNING)
           task.cancel(true);
    }
    
    0 讨论(0)
提交回复
热议问题