user7763438
user7763438

Reputation: 65

Android Java Runnable Will Not Stop

I am trying to get a simple Runnable to execute some code every few seconds, but although I can get it to execute, I cant get it to stop. The code below shows 2 calls startDbChecking() and stopDbChecking(), I have just placed them in the code block to show what I'm attempting - not how the code is set up.

public class MainActivity extends TabActivity {

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

        startDbChecking(); // will run this no problem
        stopDbChecking(); // but will not stop
    }

    public void startDbChecking() {
        handler.post(runnableCode);
    }

    public void stopDbChecking() {
        handler.removeCallbacks(runnableCode);
    }


     private Runnable runnableCode = new Runnable() {
         @Override
         public void run() { 
            // Do something here on the main thread
            System.out.println("OK");

            handler.postDelayed(runnableCode, 2000);
         }
     };
 }

Upvotes: 0

Views: 193

Answers (1)

rafsanahmad007
rafsanahmad007

Reputation: 23881

Try this in your Activity: to stop the runnable

 protected void onStop() {
    super.onStop();
    handler.removeCallbacks(runnableCode);
}

Upvotes: 1

Related Questions