james246
james246

Reputation: 1904

Android Timer thread which exits on a "is true" condition

I'm writing an Android application and I need a Timer to be set which will execute a method every one second and then stop once a boolean variable (set by aforementioned method) becomes true.

Here's an overview of what I'm trying to do:

boolean done = false;    

public void someMethod() {
    if(done == false) {
       myTimer = new Timer(); //Set up a timer, to execute TimerMethod repeatedly
       myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
               TimerMethod();
            }
        }, 0, 1000);
    }

    if(done == true) { 
        //TimerMethod will eventually set 'done' to true. When this happen, do layout modifying stuff here. Causes error as non-UI thread is executing the layout modifying stuff. Do I spawn a new UI thread here to do it? If so, how? :/
    }
}

TimerMethod() {
   String result = someServerMethod();
   if(result == "theResultWeWant") {
         myTimer.cancel(); //stop the timer - we're done!
         done = true; //set 'done' to true so the line of code in someMethod() will now run
         someMethod();
   }
}

Edit: I've updated the code above to reflect what I'd like to do. I'm hoping I can get the done flash to be set to true and then carry on executing someMethod but I'm sure it's not that simple! Do I perhaps need to spawn a new thread from TimerMethod() to execute the code from the done == true line?

Upvotes: 1

Views: 1205

Answers (1)

Joe
Joe

Reputation: 4811

All UI interactions need to be done from the main(UI) thread. In your case, you were calling someMethod() from your TimerTask which is a seperate thread. A handler is used to interact with your main thread from a helper thread.

    public void someMethod() {

          myTimer = new Timer(); //Set up a timer, to execute TimerMethod repeatedly
          myTimer.schedule(new TimerTask() {
               @Override
               public void run() {
                  TimerMethod();
               }
           }, 0, 1000);
       }

    }

    TimerMethod() {
       String result = someServerMethod();
       if(result.equals("theResultWeWant")) {
             myTimer.cancel(); //stop the timer - we're done!
             mHandler.sendEmptyMessage(0): //send message to handler to update UI
       }
    }

private Handler mHandler = new Handler(){
    public void handleMessage(Message msg) {
        doUIMethod();
    }

};

Upvotes: 3

Related Questions