Search code examples
androidandroid-activityhandler

How to make the Handler method be destroyed when the activity finishes?


At the end of this activity, the timer from the Handler method continues. How to make the Handler method be destroyed when the activity finishes?

                 Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        public void run() {
                            mTextViewCountDown.setTextColor(Color.RED);
                        }
                    }, 55000);

Solution

  • In my case I did not "destroy" the method if I leave the Activity, but the method does something only when Activity is active

    Something like this :

    // Variable of your activity
    private static boolean active = false;
    
    Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            public void run() {
                                // do something only if Activity is active
                                if(active) {
                                    mTextViewCountDown.setTextColor(Color.RED);
                                }
                            }
                        }, 55000);
    

    and set the value of active in the onStart / onStop methods :

    @Override
        public void onStart() {
            super.onStart();
            active = true;
        }
    
        @Override
        public void onStop() {
            super.onStop();
            active = false;
        }
    

    this way the code inside handler.postdelay will be executed only when your Activity is active