HandlerThread should i override run()?

gru*_*unk 3 multithreading android handler

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

PS:Asynctask不会满足我的需要,所以不要费心告诉我使用它。

谢谢

ina*_*ruk 5

我认为您没有想到HandlerThreadHandlerThread设计用于实现处理消息的线程。这意味着它Looper.loop()在其run()方法中使用了(这就是为什么您不应该覆盖它的原因)。反过来,这意味着您不必onHandleMessage()为了防止线程退出而睡觉,因为Looper.loop()已经进行了此工作。

总结一下:

  1. 不,不要覆盖run()。
  2. 您无需执行任何操作即可使线程保持活动状态。

如果您想了解/了解更多有关的信息HandlerThread,请阅读LooperHandler课程。