I am trying to make use of HandlerThread
in android and am ending up with either a situation in which the UI thread is not responding anymore, or a strange IllegalStateException
. I want to give you a minimal example of my problem.
I have a class DataManager
which instantiates a worker thread on creation:
public class DataManager
{
private final HandlerThread loaderThread = new HandlerThread( "Worker" );
private final Producer loader;
Inside of this class I have my Handler
defined:
private static class Producer extends Handler
{
public Producer( Looper looper )
{
super( looper );
}
@Override
public void handleMessage( Message msg )
{
msg.recycle();
}
}
The constructor of my DataManager
runs the worker thread and associates the handler with the thread's looper:
public DataManager()
{
loaderThread.start();
this.loader = new Producer( loaderThread.getLooper() );
}
Before DataManager
is destroyed, it stops the thread and waits for it to finish. Actually I believe this part is not relevant to my problem, because my DataManager
instance is definitely alive all the time:
@Override
protected void finalize() throws Throwable
{
loaderThread.quit();
loaderThread.join();
super.finalize();
}
Finally, I have doSomething
method, which simply posts a message to the worker thread:
public void doSomething()
{
Message msg = Message.obtain();
loader.sendMessage( msg );
}
Now I'm instantiating the DataManager
from inside of a custom view on the UI thread. When the view is about to paint itself using onDraw
it calls doSomething
on the DataManager
. The further behavior depends on whether an AsyncTask
is currently running in background or not:
- If it is running, than the UI thread is becoming unresponsive form this moment on.
- Otherwise, I get an
IllegalStateException
, thrown from within a subroutine ofLooper.loop
of the UI thread, saying:IllegalStateException: The specified message queue synchronization barrier token has not been posted or has already been removed.