天天看點

Handler類簡介及應用

一、Handler的定義

是異步通信的類,主要接受子線程發送的資料, 并用此資料配合主線程更新UI.

二、Handler主要通過Looper和MessageQueue來完成更新UI,那麼什麼是Looper和MessageQueue呢

1、Looper:

每個線程隻能夠有一個Looper,Looper負責建立并管理目前線程中的MessageQueue,調用loop方法後就會在一個無限循環體中不斷地從MessageQueue中取出Message并分發給對應的Handler,最後回調handleMessage()方法處理此消息。Looper才是整個機制的核心!

2、MessageQueue:

消息隊列,先進先出管理Message,在初始化Looper對象時會建立一個與之關聯的MessageQueue

3、Message:

其創造的message是Handler接收與處理的對象。

3、Handler更新UI的步驟:

在主線程中建立Handler并重寫handleMessage()方法在任何線程中都可以利用此Handler發送消息,消息會被發送到主線程MessageQueue中一旦MessageQueue中有新消息,主線程中的

Looper 就會發現此消息,然後就會調用Handler的handleMessage()方法處理此消息

如圖

Handler類簡介及應用

三、如何使用Handler呢

1、建立handler對象:

private  Handler handler = new Handler(){
        @Override
        //書寫handleMessage方法,用于第三步接收并處理資訊
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //這裡是發送消息後對消息進行處理
            int arg1 = msg.arg1;
            int arg2 = msg.arg2;
            String tip = (String) msg.obj;
            if (msg.what==){
                //更新UI
                downLoadTip.setText("下載下傳完成"+arg1+arg2+tip);
            }
        }
    };
           

2、發送消息

//建立子線程
new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //子線程睡眠5秒
                            Thread.sleep();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //發送更新UI的資訊
                       Message message = handler.obtainMessage();
                        //發送資訊的三種方法
                        message.what = ;      //隻能為int型
                        message.arg1 =;        //隻能為int型
                        message.arg2 = ;
                        message.obj = "keep smile";     //可以是字元串,對象等
                        handler.sendMessage(message);
                    }
                }).start();    //啟動線程
           

3、接收并處理消息

private  Handler handler = new Handler(){
        @Override
        //書寫handleMessage方法,用于第三步接受資訊
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //這裡是發送消息後對消息進行處理
            int arg1 = msg.arg1;
            int arg2 = msg.arg2;
            String tip = (String) msg.obj;
            if (msg.what==){
                //更新UI
                downLoadTip.setText("下載下傳完成"+arg1+arg2+tip);
            }
        }
    };
           

四、使用handler類完成倒計時案例

1、建構倒計時布局activity_ji_shi.xml,注意設定ID

<?xml version="1.0" encoding="utf-8"?>
<!--建構倒計時布局,注意設定ID-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication.JiShiActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:gravity="center"
            android:textSize="20sp"
            android:text="設定時間"/>

        <EditText
            android:id="@+id/edit_et"
            android:layout_width="52dp"
            android:layout_height="match_parent" />

        <TextView
            android:layout_width="30dp"
            android:layout_height="match_parent"
            android:textSize="20sp"
            android:gravity="center"
            android:text="秒"/>


    </LinearLayout>


    <TextView
        android:id="@+id/daojishi_tv"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:text="倒計時:"
        android:textSize="20sp"
        android:layout_centerInParent="true"
        android:gravity="center"/>

    <TextView
        android:id="@+id/current_tv"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:text=""
        android:textSize="20sp"
        android:gravity="center"
        android:layout_alignTop="@+id/daojishi_tv"
        android:layout_toRightOf="@+id/daojishi_tv" >

    </TextView>

    <Button
        android:id="@+id/start_btn"
        android:layout_width="wrap_content"
        android:text="開始計時"
        android:layout_below="@+id/daojishi_tv"
        android:layout_alignLeft="@+id/daojishi_tv"
        android:gravity="center"
        android:layout_height="50dp" />



</RelativeLayout>
           

2、/在JiShiActivity中完成對EditText、TextView、Button的綁定,并完成對button按鈕的監聽,按鈕監聽事件中完成子線程的建立,和通知主線程更新UI

public class JiShiActivity extends AppCompatActivity {
    //建立handler對象
    private Handler handler = new Handler() {
        @Override
        //書寫handleMessage方法,接受資訊
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what!=){
                currentTV.setText(msg.what + "");
            }else{
                //通知主線程更新UI
                currentTV.setText("計時結束");
            }

        }
    };
    //定義控件
    private EditText editText;
    private TextView currentTV;
    private Button startBtn;
    //定義全局變量i,用于for語句
    private int i;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ji_shi);
        bangID();
        //對button按鈕進行監聽
        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //擷取editText中輸入的值,裝換成字元串
                String str = editText.getText().toString();
                //将字元串轉換成int型
                i = Integer.parseInt(str);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //使用for語句實作倒計時
                        for (int time = i; i>||i ==; i--) {
                            Message message = handler.obtainMessage();
                            message.what = i;
                            handler.sendMessage(message);
                            try {
                                Thread.sleep();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();

            }
        });
    }

    private void bangID() {
        editText = findViewById(R.id.edit_et);
        currentTV = findViewById(R.id.current_tv);
        startBtn = findViewById(R.id.start_btn);

    }
}
           

效果展現

Handler類簡介及應用