Thread that executes
Looper#loop() with optional iteration period. Looper thread has convenient methods to
start and stop thread execution and supports two iteration modes:
continuous
and
periodic
.
In continuous
mode looper thread executes loop iterations with processor speed. Looper instance is
usually waiting for some IO, takes care itself to sleep for some time or really has much computation to do. It is
looper instance responsibility to ensure processor is not abused.
To enable periodic
mode one should use a constructor that supplies a period value. Looper thread
executes internal sleep and invoke iteration with requested period. Implementation takes care to compensate for
iteration processing time but if it takes more that requested period looper thread works again in continuous mode.
In any case, looper implementation should consider that thread checks for running state between loops - for this
reason blocking read operations are not allowed.
For your convenience here is a sample code.
class DemoLooper implements Looper, AsyncExceptionListener
{
private LooperThread thread;
DemoLooper()
{
tread = new LooperThread(this);
thread.start();
}
void stop()
{
thread.stop();
}
void loop() throws Exception
{
// execute iteration logic
}
void onAsyncException(Throwable throwable)
{
// handle loop iteration exception
}
}
Since looper is running in a separated thread is not possible to catch exceptions. If interested in handling loop
iteration exception one should make looper implementing
AsyncExceptionListener. It is also possible to set
exception listener after looper thread creation, even after thread start, using
#setExceptionListener(AsyncExceptionListener).
Looper thread runs till explicit
#stop(). This is true even if a loop execution throws exception; default
behavior is to dump stack and continue loop iterations. Anyway, if desirable to break the loop on exception one can
use
#setBreakOnException(boolean) to set
#breakOnException flag to true.