Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading