How to stop Runnable when a button is clicked on Android?

I need to run runnable when I press the start button and stop it when I press the pause button. My code to start the launch when the start button is clicked

// TODO Auto-generated method stub //while (running) { mUpdateTime = new Runnable() { public void run() { sec += 1; if(sec >= 60) { sec = 0; min += 1; if (min >= 60) { min = 0; hour += 1; } } Min_txtvw.setText(String.format(mTimeFormat, hour, min, sec)); mHandler.postDelayed(mUpdateTime, 1000); } }; mHandler.postDelayed(mUpdateTime, 1000); //} 

Now I want to stop this start button when paused by pressing

pause_btn.setOnClickListener (new OnClickListener () {

  @Override public void onClick(View v) { // TODO Auto-generated method stub play_btn.setVisibility(View.VISIBLE); pause_btn.setVisibility(View.INVISIBLE); } }); 

How can I stop this button when I press the pause button, if anyone knows, please help me.

+6
source share
4 answers

Use

 mHandler.removeCallbacksAndMessages(runnable); 

press the pause button.

+13
source

Save the boolean cancelled flag to keep the status. Initialize it to false, and then change it to true by clicking the Stop button.

And inside your run() method, keep checking this flag.

Edit

The approach usually works, but still not the most suitable way to stop runnable / thread. There may be a situation where the task is locked and cannot check the flag, as shown below:

  public void run(){ while(!cancelled){ //blocking api call } } 

Suppose the task makes a blocking api call and then the flag is canceled. The task will not be able to check the status change until an API lock call is made.

Alternative and safe approach

The most reliable way to stop a thread or task (Runnable) is to use an interrupt mechanism. Interruption is a collaboration mechanism to ensure that stopping a thread does not leave it in an inconsistent state.
On my blog, I discussed in detail the interrupt link .

+7
source

Use the code below:

 handler.removeCallbacks(runnable); 
0
source

Thread theme; // inside the start button

  thread=new Thread(new Runnable() { @Override public void run() { sec += 1; if(sec >= 60) { sec = 0; min += 1; if (min >= 60) { min = 0; hour += 1; } } Min_txtvw.setText(String.format(mTimeFormat, hour, min, sec)); mHandler.postDelayed(mUpdateTime, 1000); }); thread.start(); 

// internal stop button

 mHandler.removeCallbacksAndMessages(runnable); thread.stop(); 
-2
source

Source: https://habr.com/ru/post/943521/


All Articles