kostrykin
kostrykin

Reputation: 4292

Android: posting message to HandlerThread makes UI thread unresponsive or gives IllegalStateException

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:

Google gives absolutely no results for this message. I've been reading documentation and searching for similar problems for a few hours now and still have no idea what I might be doing wrong. Any ideas?

Upvotes: 2

Views: 3098

Answers (1)

kostrykin
kostrykin

Reputation: 4292

Got it. Obsiously the situation about recycling messages is this:

If you send it to a handler, the handler/looper will recycle it for you.

So one must not recycle the message within handleMessage.

Upvotes: 6

Related Questions