'How to make the Handler method be destroyed when the activity finishes? [duplicate]

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 1:[1]

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

Solution 2:[2]

you can you use onDestory(); lifecycle method.this method calls when an activity going to finish and in this activity lifecycle method you and stop the handler like this

@Override 
protected void onDestroy() {

Handler handler = new Handler();

handler.postDelayed(new Runnable());

super.onDestroy();

}```

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Larvouu
Solution 2