开发者

HandlerThread should i override run()?

I'm trying to use the HandlerThread class to manage thread in my application. The following code is working great :

public class ThreadA extends HandlerThread
{
    private void foo()
    {
        //do something
    }

    private void bar()
    {
        //Do something else
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch(msg.what)
        {
            case 1:
            {
                this.foo();
                break;
            }

            case 2:
            {
                this.bar();
                break;
            }
        }
        return false;
    }

    @Override
    protected void onLooperPrepared()
    {
        super.onLooperPrepared();
        synchronized (this) {
            this.AHandler = new Handler(getLooper(),this);
            notifyAll();
        }
    }
}

1- Should i override the run() method ? In a "classic" thread most of the code is located in the run method.

2- Lets imagine i need my foo() method to be a infinite process (getting a video streaming for example). What's the best solution ?

  • Overriding run with my foo() code ?
  • Simply adding a sleep(xxx) in foo() :

    private void foo() { //do something sleep(100); foo(); }

-Using a delayed message like :

private void foo()
{
    //do something
    handler.sendEmptyMessageDelayed(1,100);
}

PS : Asynctask开发者_JS百科 will not cover my need , so do not bother to tell me to use it.

Thanks


I think you didn't get the idea of HandlerThread. HandlerThread is designed to implement thread that handles messages. What this means is that it uses Looper.loop() in its run() method (and that's why you shouldn't override it). This in turn means that you don't need to sleep in onHandleMessage() in order to prevent thread from exiting, as Looper.loop() already takes care of this.

To summarize:

  1. No, do not override run().
  2. You don't need to do anything to keep thread alive.

If you want to learn/undestand more about HandlerThread, read about Looper and Handler classes.


You shouldn't override the run method in the HandlerThread since that is where the core functionality of the class actually occurs. Based on what you are showing, I also see no reason to do so.

If your task itself is infinite, there isn't anything preventing you from having it execute that way. The only reason you might want to use handler.sendEmptyMessageDelayed is if you plan to have other tasks that you want run queued on the HandlerThread while foo() is executing. The other approach you recommended will prevent the HandlerThread from handling any other message. That being said, I suspect there is a better way to make your task infinite.

Finally, you should remember to stop your infinite task and call HandlerThread.getLooper().quit() to make sure your HandlerThread stops nicely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜