首页 > 代码库 > Handler消息传递机制(三)管理MessageQueue的Looper

Handler消息传递机制(三)管理MessageQueue的Looper

package com.example.looper;

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

public class MainActivity extends Activity {

	private Button send;
	private TextView textView;
	private MyHandler myHandler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		send = (Button) findViewById(R.id.button1);
		textView = (TextView) findViewById(R.id.textView1);
		Looper looper = Looper.myLooper();
		myHandler = new MyHandler(looper);
		//也可用无参构造方法,系统会有一个默认的Looper来管理消息队列
		send.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// 启动线程
				new Thread(new MyThread()).start();
			}
		});
	}
  
	public class MyHandler extends Handler{
		public MyHandler() {
			
		}
		public MyHandler(Looper looper) {
			super(looper);
		}
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			textView.setText("--obj-->>" + msg.obj);
		}
	}
	public class MyThread implements Runnable{

		@Override
		public void run() {
			Message message = Message.obtain();
			message.what = 1;
			message.obj = "Rose";
			myHandler.sendMessage(message);
		}
	}
}

<RelativeLayout 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.example.looper.MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="56dp"
        android:text="发送消息" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="119dp"
        android:textSize="30dp"
        android:text="TextView" />

</RelativeLayout>

技术分享

点击子线程发送消息,主线程接收消息并更新UI

技术分享

使用默认looper样例

使用自定义Looper案例

Handler消息传递机制(三)管理MessageQueue的Looper