Android UI編程(6)——HandlerThread

來源:互聯網
上載者:User

標籤:looper   handler   message   handlerthread   

介紹:

HandlerThread繼承Thread,當線程開啟時,也就是它run方法運行起來後,線程同時建立了一個含有訊息佇列的Looper,並對外提供自己這個Looper對象的get方法,這就是它和普通Thread唯一不同的地方。

好處:

為什麼要使用HandlerThread

1、開發中如果多次使用類似new Thread(){}.start(); 這種方式開啟一個子線程,會建立多個匿名線程,使得程式運行越來越慢,而HandlerThread內建Looper使他可以通過訊息來多次重複使用當前線程,節省開支

2、android系統提供的Handler類內部的Looper預設綁定的是UI線程的訊息佇列,對於非UI線程又想使得訊息機制,那麼HandlerThread內部的Looper是最合適的,它不會干擾或阻塞UI線程

用法:

HandlerThread既然本質是Thread,為何前面加了一個Handler?android中Handler類本質上就是從它內部的Looper中不斷取訊息,然後觸發它內部的Callback介面的handleMessage方法,讓使用者去實現對訊息的具體處理。而HandlerThread本身內建Looper,只要它實現了Callback介面,那麼HandlerThread也可以在自己線程內處理線程發出的訊息,充分實現非UI線程中較低開支下的訊息處理。

總結:

1、HandlerThread繼承Thread,與Thread不同就是提供自己的Looper對象,不過需要先啟動這個HandlerThread線程

2、調用handlerThread.getLooper()來擷取Looper對象,則不要調用Looper.prepare()和Looper.loop()方法

要更好的理解Looper以及HandlerThread,先查看Android UI編程(5)——Looper

AndroidManifest.xml——沒有做任何修改,建立工程預設產生的

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.wxl.handlerthread"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="19" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.wxl.handlerthread.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>
activity_main.xml

<LinearLayout 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:gravity="center"    android:orientation="vertical"    tools:context=".MainActivity" >    <TextView        android:id="@+id/textView"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />        <Button         android:id="@+id/button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="發送hello world"/></LinearLayout>
MainActivity.java

package com.wxl.handlerthread;import android.os.Bundle;import android.os.Handler;import android.os.HandlerThread;import android.os.Looper;import android.os.Message;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.app.Activity;public class MainActivity extends Activity {private TextView textView;private Button button;private Handler handler;private MyThread myThread;private HandlerThread handlerThread;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView = (TextView)this.findViewById(R.id.textView);        button = (Button)this.findViewById(R.id.button);        button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubMessage message = Message.obtain();message.what = 1;message.obj = "hello world";handler.sendMessage(message);}});        myThread = new MyThread();        handlerThread = new HandlerThread("");        myThread.start();        handlerThread.start();    }    public class MyThread extends Thread {    @Overridepublic void run() {// TODO Auto-generated method stubsuper.run();Looper.prepare();handler = new Handler(handlerThread.getLooper()){    @Override    public void handleMessage(Message msg) {    // TODO Auto-generated method stub    super.handleMessage(msg);    if (1 == msg.what)    {    //textView.setText(""+msg.obj);子線程不能更新UI    Log.i("", ""+msg.obj);    }    }    };    Looper.loop();}    }}
點擊按鈕:





Android UI編程(6)——HandlerThread

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.