Search code examples
androidandroid-asynctaskandroid-fragmentsandroid-activity

How to stop an AsyncTask in a Fragment after the Application closes


How to stop AsyncTask in Fragment class after closing the application?

MainActivity class

public class MainActivity extends FragmentActivity {

}

BaseFragment class extends by Fragment

public class BaseFragment extends Fragment {
    public MainActivity mActivity;
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mActivity       =   (ChatActivity)this.getActivity();
    
    }
    
    public boolean onBackPressed(){
        return false;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data){
        
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    
}

Fragment class

public class Fragment1 extends BaseFragment{


private  Update  task;
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        
        toCallAsynchronous();

        return inflater.inflate(R.layout.activity_online_korisnici, container,
                false);
    }


     public void toCallAsynchronous() {
            final Handler handler = new Handler();
            Timer timer = new Timer();
            TimerTask doAsynchronousTask = new TimerTask() {       
                @Override
                public void run() {
                    handler.post(new Runnable() {
                        public void run() {       
                            try {
                             task =new Update();
                             
                                // PerformBackgroundTask this class is the class that extends AsynchTask 
                                task.execute("");
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                            }
                        }
                    });
                }
            };
            timer.schedule(doAsynchronousTask, 0, 5000); //execute in every 50000 ms
        }




   private class Update extends AsyncTask<Object, Object, List<Object>>{

    @Override
        protected List<Object> doInBackground(Object... params) {
                     
                 }

@Override
        protected void onPostExecute(List<Object> result) {


}

   }


}

Solution

  • You can use onPause() method of your Fragment. It is called when the Fragment is no longer resumed. This is generally tied to Activity.onPause of the containing Activity's lifecycle.

    @Override
    public void onPause() {
        super.onPause();
        task.cancel();
    }
    

    Update: If you are under TabHost, and the Fragment is paused when pressed different tabs, you could do so

    store fragment id's or tags in your activity

    implement a method to stop task in your fragments

    public void onActivityPause() {
        task.cancel();
    }
    

    In your activity onPause()

    @Override
    protected void onPause() {
        super.onPause();
        FragmentManager fm = getFragmentManager();
        for (int id : ids) {
            Fragment f = fm.findFragmentById(id);
            try {
                Method stop = f.getClass().getMethod("onActivityPause");
                close.invoke(f);
            } catch (Exception e) {}
        }
    }
    

    But I wouldn't use TabHost anyway, it's deprecated. Consider using ActionBar, or ActionBarSherlock if you need to support v4 versions.