Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

第80章:Handle-Message-Looper 消息機制之一——基礎用法(從零開始學 Android)

編輯:Android 技術基礎

本章我們先打基礎,好好認識一下 Handler、Message、Looper 這三兄弟的用法。理解它們如何搭配,是日後處理多線程與 UI 更新的關鍵一步。

一、設計界面

1. 佈局檔

打開 res/layout/activity_main.xml,放兩顆按鈕與一個文字元件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnmain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自主線程發送消息給自己" />

    <Button
        android:id="@+id/btnother"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自其它線程發送消息至主線程" />

    <TextView
        android:id="@+id/tvmsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>

二、程式檔

打開 src/com.genwoxue.handlemessageloop/MainActivity.java。這個例子示範兩種情境:主線程給自己發消息,以及子線程把消息送到主線程。

package com.genwoxue.handlemessageloop;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity{

    private static long s=0;
    private String TAG = "HandlerTest";
    private ReceiveMessageThread receiveMessageThread =null;
    private EventHandler mHandler = null;

    private Button btnMain = null;
    private Button btnOther = null;
    private TextView tvMsg = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnMain = (Button)super.findViewById(R.id.btnmain);
        btnOther = (Button)super.findViewById(R.id.btnother);
        tvMsg = (TextView)super.findViewById(R.id.tvmsg);

        btnMain.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v){
                //主線程發送消息給自己
                Looper looper = Looper.myLooper(); //get the Main looper related with the main thread
                //如果不給任何參數的話會用當前線程對應的Looper(這裡就是Main Looper)為Handler裡面的成員mLooper賦值
                mHandler = new EventHandler(looper);
                // 清除整個MessageQueue裡的消息
                mHandler.removeMessages(0);
                String obj = "This main thread's message and received by itself!";

                Message msg = mHandler.obtainMessage(1,1,1,obj);
                // 將Message對象送入到main thread的MessageQueue裡面
                mHandler.sendMessage(msg);
            }
        });

        btnOther.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v){
                //other線程發送消息給主線程
                receiveMessageThread = new ReceiveMessageThread();
                receiveMessageThread.start();
            }
        });

    }


    class EventHandler extends Handler{

        public EventHandler(Looper looper){
            super(looper);
        }

        public EventHandler(){
            super();
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.e(TAG, "CurrentThread id:----------+>" + Thread.currentThread().getId());
            switch(msg.what){
            case 1:
                tvMsg.setText((String)msg.obj);
                break;
            default:
                Log.e(TAG,(String)msg.obj);
                break;
            }
        }

    }

    //ReceiveMessageThread has his own message queue by execute Looper.prepare();
    class ReceiveMessageThread extends Thread {

        @Override
        public void run(){
            Looper.prepare();

            Looper looper = Looper.getMainLooper();
            mHandler = new EventHandler(looper);
            mHandler.removeMessages(0);

            s=s+1;
            Message msg =new Message();
            msg.what=1;
            msg.obj=String.valueOf(s);
            // 將Message對象送入到main thread的MessageQueue裡面
            mHandler.sendMessage(msg);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Looper.loop();
        }
    }

}

三、設定檔

打開 AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.genwoxue.handlemessageloop"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="15" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.genwoxue.handlemessageloop.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>

採用預設的 AndroidManifest.xml 即可,無須額外配置。

四、運行結果

按下第一顆按鈕,主線程會給自己送出一則消息並在文字元件上顯示;按下第二顆按鈕,子線程則會每隔一秒把累加的數字送到主線程更新畫面。透過 LogCat 你還能觀察到 handleMessage() 究竟在哪條線程上被執行——這正是理解「消息在哪裡發、又在哪裡收」的最佳教材。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved