Home > Mobile >  Stopping a running void in java
Stopping a running void in java

Time:10-19

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

}


  }
}

CodePudding user response:

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.

CodePudding user response:

volatile bool condition = false;
public void _blink()
{
    if (condition == true) return;
}
public void _stop()
{
    condition = true;
}
  • Related