0

I love the convenience of the Handler class; I can easily queue messages and even delay messages. However, all the code runs on the UI thread which is causing stuttering of the animation.

Is there a class, like Handler, that doesn't run on the UI thread ?

4

2 回答 2

0

You could always use a HandlerThread. I do not have a simple example of this handy, unfortunately.

Personally, I tend to use java.util.concurrent classes directly for things that do not involve the main application thread (e.g., LinkedBlockingQueue, ExecutorService).

于 2012-10-07T11:12:24.677 回答
0

I'm a little confused by the currently accepted answer which seems to imply that using Handler on a non-UI thread isn't possible, because it's something I've done quite routinely and I thought it was pretty well known.

Within a non-UI Thread:

    @Override
    public void run() {
        Looper.prepare();
        ...
        mThreadHandler = new Handler() {            
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    ...
                        break;
                    default:
                        break;
                }
            }
        };
        Looper.loop();
    }

Using the mThreadHandler, messages can be sent to be processed by the Handler in the above non-UI Thread.

If there are any good reasons for not using the Handler / Message classes to post work to be done on a non-UI Thread in this way then I'd like to know. It has been working fine for me so far though. The only reason I've read for not using a Handler in this way is that "a Handler is meant for posting stuff to the UI thread" which is not in itself a good technical basis.

于 2012-12-11T11:36:21.993 回答