Stop AsyncTask in Fragments when Back Button is pressed

前端 未结 5 1505
别跟我提以往
别跟我提以往 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: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);
        }
    }
    

提交回复
热议问题