how to continuously test whether a handler's runnable is finished?

1.5k Views Asked by At

How can Android code to detect when a handler's runnable process is completed? In this particular application, no other events are generated other than the handler finishing its work.

Simply putting a while() loop around a continuous test of a global boolean flag doesn't seem to work:

... stuff to do before the handler's runnable is started
while (globalBooleanFlagStatingThatRunnableIsNotYetFinished)
                     Thread.sleep(5);
... stuff to do only after the handler's runnable is finished, like process data

Using the while() approach, it appears that execution pauses forever at the semicolon until a force close is pushed by the OS, regardless of the success of the runnable to set said boolean flag.

How have others detected the completion of a runnable process?

2

There are 2 best solutions below

0
On

Your while loop hogs all the cpu time so nothing else, like UI messages, have time to be processed.

The usual fix is ti put a short Sleep() inside the loop. This results in a call to the kernel allowing it to run other task bits for a while.

Other I/O such as console prints an file read/writes also do this.

0
On

The fact that you are busy waiting, or in fact waiting at all indicates that there may be something flawed in the design philosophic of your app. Typically, if you are waiting for something, what you should be instead doing is triggering an action as a response to some handler. For example, in this case, you may simply be able to handle an onClick event. In the case that you are waiting on this in a thread, why? Instead, kill the thread, leave some state around (by means of a state machine, implementing a continuation), and when onClick is called, start a new task to perform the rest of the work.

Basically, I'm not sure I buy that you actually need to be waiting here, instead you should be using a handler.

EDIT: The kind of programming you're looking for isn't possible on the main thread of the application. Instead what you should be doing is using an AsyncTask, where you do the work in the task (i.e., turn on the flash and off the flash in regular intervals) or a Service which spawns a thread. In any case, you should read up on Android threading, your problem likely relates to you trying to use the main thread for long running operations. And yes, this is possible, but I wouldn't call it "real time programming," this is just a simple threading issue.