Search code examples
androidandroid-handlerthread

How to Stop Handler thread?


I want to stop this thread on button click.

TIME_OUT = 45000;
new Handler().postDelayed(new Runnable() {
       @Override
       public void run() {
         Intent i = new 
         Intent(MapsActivity.this,MapsActivity.class);
         startActivity(i);
         finish();
       }
     }, TIME_OUT);

I am using above handler in onCreate of an Activity. I want to stop it. How to stop this thread on click of any button or on click of on Back Pressed?


Solution

  • Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Intent i = new
                    Intent(MapsActivity.this,MapsActivity.class);
            startActivity(i);
            finish();
        }
    };
    handler.post(runnable);
    
    // use this when you don't want callback to be called anymore
    handler.removeCallbacks(runnable);