0

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);
ADM
  • 20,406
  • 11
  • 52
  • 83
Biron1gg
  • 87
  • 1
  • 10

2 Answers2

0

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

Larvouu
  • 132
  • 12
0

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();

}```
n_dev
  • 101
  • 8