0

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?

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
Ankesh Roy
  • 278
  • 2
  • 8
  • 33

4 Answers4

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

Then you can use Handler#removeCallbacksAndMessages to remove this or any callback.

handler.removeCallbacksAndMessages(null);
Alex Chengalan
  • 8,211
  • 4
  • 42
  • 56
3

Okay the best option is to use a boolean as a flag like that

TIME_OUT = 45000;

//add this boolean
boolean run =true;

new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                //run this method only when run is true
                 if(run==true){

                    //your code
                   }

            }
        }, TIME_OUT);

             //on button click just change the boolean to flag and it will stop the run method
              //on click
              run=false;
Hasan Bou Taam
  • 4,017
  • 2
  • 12
  • 22
2
public class MainActivity extends Activity{
Handler handler;
Button b;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       

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

button1=(Button)findViewById(R.id.button1);  
        button1.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View arg0) {  
               handler.removeCallbacks(runnable);  
            }  
        });  

   
}


 
}
Chandra Shekhar
  • 3,550
  • 2
  • 14
  • 22
Dilip
  • 2,622
  • 1
  • 20
  • 27
1
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);
JiratPasuksmit
  • 672
  • 7
  • 18