天天看點

Android HandlerThread 使用介紹及簡單解析

一 先看看官方介紹:

(1)HandlerThread繼承自線程Thread,内部封裝了有Looper。

Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.
           

(2)常用方法:

、Looper    getLooper()//傳回一個與目前線程關聯的Looper
This method returns the Looper associated with this thread.
2、int   getThreadId()
Returns the identifier of this thread.
3、boolean   quit()       // HandlerThread退出資源
Quits the handler thread's looper.
4、boolean   quitSafely()
Quits the handler thread's looper safely.
5、void  run()    //執行方法(工作線程)
If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
           

二 HandlerThread DEMO

布局檔案:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.troy.handlerthreaddemo.MainActivity">

    <LinearLayout
        android:id="@+id/ll_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="22dp"
            android:layout_marginBottom="18dp"
            android:text="三峽日洩洪流量時刻表" />
    </LinearLayout>

</ScrollView>
           

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    private TextView tv;
    private HandlerThread mCheckMsgThread; //HandlerThread 
    private Handler mCheckMsgHandler;   //工作線程的Handler
    private boolean isUpdateInfo;
    private static final int MSG_UPDATE_INFO = ;
    private Handler mUIHandler=new Handler();//與UI線程管理的Handler
    private LinearLayout ll_container;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=(TextView)findViewById(R.id.tv);
        ll_container=(LinearLayout)findViewById(R.id.ll_container);

        initBackThread();//建立工作線程
    }

    private void initBackThread(){
        mCheckMsgThread=new HandlerThread("check-message-coming");
        mCheckMsgThread.start();
        mCheckMsgHandler=new Handler(mCheckMsgThread.getLooper()){
            @Override
            public void handleMessage(Message msg) {
                Log.i("TEST","msg.what :"+msg.what);
                checkForUpdate();
                if(isUpdateInfo){
                    mCheckMsgHandler.sendEmptyMessageDelayed(MSG_UPDATE_INFO,);//自己觸發自己
                }
            }
        };
    }

    private void checkForUpdate(){
        try{
            Thread.sleep();
            mUIHandler.post(new Runnable() {
                @Override
                public void run() {
                    Date date=new Date();
                    DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String time=format.format(date);
                    String result="目前洩洪流量:  <font color='red'>%d</font>  立方/秒  &nbsp;&nbsp;&nbsp; <font color='gray'>%s</font>";
                    result=String.format(result,(int)(Math.random()*+),time);
                    TextView textView=new TextView(MainActivity.this);
                    textView.setTextSize();
                    textView.setPadding(,,,);
                    textView.setText(Html.fromHtml(result));
                    ll_container.addView(textView);
                }
            });
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume(){
        super.onResume();
        //開始查詢
        isUpdateInfo = true;
        mCheckMsgHandler.sendEmptyMessage(MSG_UPDATE_INFO);
    }

    @Override
    protected void onPause(){
        super.onPause();
        //停止查詢
        isUpdateInfo = false;
        mCheckMsgHandler.removeMessages(MSG_UPDATE_INFO);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //釋放資源
        mCheckMsgThread.quit();
    }
}
           

運作結果如下:

Android HandlerThread 使用介紹及簡單解析

三 源碼分析:

HandlerThread.java:

HandlerThread的建立:

public HandlerThread(String name) {//構造方法
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }

    public HandlerThread(String name, int priority) {//可設定線程優先級 int THREAD_PRIORITY_DEFAULT // 預設應用的優先級
        super(name);
        mPriority = priority;
    }
           

HandlerThread的啟動:

@Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);//設定線程的優先級
        onLooperPrepared();
        Looper.loop();//開啟消息循環
        mTid = -;
    }
           

可以看到run()方法中調用了Looper.prepare(),Loop.loop();

prepare()呢,中建立了一個Looper對象,并且把該對象放到了該線程範圍内的變量中(sThreadLocal),在Looper對象的構造過程中,初始化了一個MessageQueue,作為該Looper對象成員變量。loop()就開啟了,不斷的循環從MessageQueue中取消息處理了,當沒有消息的時候會阻塞,有消息的到來的時候會喚醒。

那麼,mCheckMsgThread.getLooper()做了什麼:

/**
     * This method returns the Looper associated with this thread. If this thread not been started
     * or for any reason is isAlive() returns false, this method will return null. If this thread 
     * has been started, this method will block until the looper has been initialized.  
     * @return The looper.
     */
    public Looper getLooper() {
        if (!isAlive()) {
            return null;
        }

        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                try {
                    wait();//如果mLooper為空的時候,就等待,直到 mLooper = Looper.myLooper(); 由notifyAll();來喚醒;
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }
           

mCheckMsgThread.getLooper()傳回的就是我們在run方法中建立的mLooper。

參考緻謝:

1 Android HandlerThread 完全解析