Stopping a running void in java

164 Views Asked by At

What's the way to stop a running method in Java?

I have a method called main in my MainActivity.java file and also I have two methods into it. They are blink() [which is a forever loop] and stop() . after a button(id=btn1) clicked I call the method blink() and I have an another button (id=btn2), on clicking on this button It will call the method stop(). Now I want that when ever i click on the button(btn2) the running method blink() will be stopped exactly on that moment.

What I actually need is -

public class MainActivity extends Activity {
    TextView tv1;
    Button btn;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        @Override
        public void onClick(View _view) {
            _blink();
        }

        @Override
        public void onClick(View _view) {
            _stop();
        } 

        public void _blink() {
            // Here is my code which I want to perform as a forever loop
        }

        public void _stop() {
            //here I want the code which will stop the running method blink()
        }
    }
}
2

There are 2 best solutions below

6
Kęstutis Ramulionis On
volatile bool condition = false;
public void _blink()
{
    if (condition == true) return;
}
public void _stop()
{
    condition = true;
}
1
Kris On

You can solve it with a flag variable itself right ? See below:

public class MainActivity extends Activity 
{
    
    TextView tv1;
    Button btn;
    private boolean isBlinking=false;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    @Override
    public void onClick(View _view) {
      _blink();
}

    @Override
    public void onClick(View _view) {
      _stop();
} 

public void _blink(){
  this.isBlinking = true;
  while(this.isBlinking){...}
//here is my code which I want to perform as a forever loop


}

public void _stop(){
  this.isBlinking = false;

  //here I want the code which will stop the running method blink()

}

This works, if the activity runs as a thread (I'm not an Android guy :-) ). Otherwise, you have to run the _blink() in a thread and check the flag inside the loop of thread.