Android Multithreading: HandlerThread understand and use summary

A, Android in HandlerThread

1.1 The main role

And other data updated every few seconds or pictures.

1.2 Principle

Inherited Thread, is actually a Looper, Handler's threads.

  1. Inherited Thread, in the run()process by Looper.prepare()creating a message queue, Looper.loop()to process the message loop.
  2. When using open HandlerThread, create Handler and HandlerThread binding of Looper, Handler message notification HandlerThread way to perform a specific task.

1.3 Features

Internal HandlerThread maintains a message queue, to avoid repeatedly create and destroy child thread to operate.

Two, HandlerThread use

2.1 HandlerThread use steps

(1) create HandlerThread instance, the name of the parameter string to define a new thread.

 

HandlerThread mHandlerThread = new HandlerThread("check-message-coming");

(2) Start HandlerThread thread.

 

mHandlerThread.start(); 

(3) create a Handler object, HandlerThread the Lopper as a parameter, thus completing the binding Looper object Handler object HandlerThread of (here Handler objects can be seen as binding HandlerThread child thread, so handlerMessage in operation It is running in the sub-thread). HandleMessage rewriting process time-consuming operation.

 

Handler mCheckMsgHandler = new Handler(mHandlerThread.getLooper()){
     @Override
     public void handleMessage(Message msg){
         // 进行耗时操作
     }
};

So that we can process the message object as mCheckMsgHandler to perform time-consuming operation, after the completion handler may switch to the main thread to update the UI.

2.2 HandlerThread use examples

According to the steps just to implement a function to update the data per second, this function can be used to update the stock, commodity prices.

  1. Create and start HandlerThread, handler bindings : new Activity, the onCreate()conduct in using a initBackThread()created HandlerThread method. MCheckMsgHandler message waiting to start the simulation obtained after the switching operation is completed takes to update the UI to the UI thread, the main thread Handler is the same.

 

    private void initBackThread(){
        // 1.创建HandlerThread
        mHandlerThread = new HandlerThread("check-message-coming");
        // 2.启动HandlerThread线程
        mHandlerThread.start();
        // 3.创建Handler对象绑定该线程的Looper
        mCheckMsgHandler = new Handler(mHandlerThread.getLooper()){
            @Override
            public void handleMessage(Message msg){
                //模拟耗时操作
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 主线程更新数据
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String result = "每隔1秒更新一下数据:"+Math.random();
                        mInfoText.setText(result);
                    }
                });

                if(isUpdate){ //1s后再次发送消息进行耗时操作
                    mCheckMsgHandler.sendEmptyMessageDelayed(MSG_UPDATE_INFO, 1000);
                }
            }
        };
    }
  1. Button to send a message using Binding Handler : a start button to send the message to mCheckMsgHandler time-consuming operation, another button stops sending messages. Mark isUpdate whether to send a message updates again.

 

        mInfoText = (TextView) findViewById(R.id.tv_info_count);
        findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开始更新
                isUpdate = true;
                mCheckMsgHandler.sendEmptyMessage(MSG_UPDATE_INFO);
            }
        });

        findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //停止更新
                isUpdate = false;
                mCheckMsgHandler.removeMessages(MSG_UPDATE_INFO);
            }
        });
  1. To remember onPause()and onDestroy()pause and stop mHandlerThread update to release memory.

 

    @Override
    protected void onPause() {
        super.onPause();
        isUpdate = false;
        mCheckMsgHandler.removeMessages(MSG_UPDATE_INFO);
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        //释放资源
        mHandlerThread.quit();
    }

Related articles:
Android Multithreading: understand and use simple summary
Handler vs Timer, which is what the use?

Reprinted: https://www.jianshu.com/p/a03ef2a0c026

Published 49 original articles · won praise 2 · Views 8588

Guess you like

Origin blog.csdn.net/yangjunjin/article/details/105030711