HandlerThread的使用及原理

HanlderThread继承自Thread,HandlerThread能够新建拥有Looper的线程,它的run()中通过Looper.prepare()创建了消息队列,并通过Looper.loop()开启了消息循环,这样我们就可以在HandlerThread中创建Handler

public class MainActivity extends AppCompatActivity {
    /**
     * 工作消息标志
     */
    private final static int MSG_WORK = 0x01;
    private Handler       mHandler;
    private HandlerThread mHandlerThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mHandlerThread = new HandlerThread("HandlerThread");
        mHandlerThread.start();     //开始线程
        mHandler = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                try {
                    Thread.sleep(3000);     //模拟延时操作
                    Log.e(Thread.currentThread().getName(), (int) (Math.random() * 3000 + 1000) + "");
                    mHandler.sendEmptyMessageDelayed(MSG_WORK, 1000);   //延时一秒发送工作消息
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        mHandler.sendEmptyMessage(MSG_WORK);    //发送工作消息,触发消息Handler执行
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(MSG_WORK);      //移除队列中为执行的工作消息
        mHandlerThread.quit();      //退出线程
    }
}

你可能感兴趣的:(HandlerThread的使用及原理)