Android异步处理:Handler+Looper+MessageQueue深刻详解

转载自:http://blog.csdn.net/mylzc/article/details/6771331,在原文基础上修改整理再发布。java

概述:Android使用消息机制实现线程间的通讯,线程经过Looper创建本身的消息循环,MessageQueue是FIFO的消息队列,Looper负责从MessageQueue中取出消息,而且分发到消息指定目标Handler对象。Handler对象绑定到线程的局部变量Looper,封装了发送消息和处理消息的接口。android

例子:在介绍原理以前,咱们先介绍Android线程通信的一个例子,这个例子实现点击按钮以后从主线程发送消息"hello"到另一个名为” CustomThread”的线程。app

Log打印结果: 异步


原理:ide

咱们看到,为一个线程创建消息循环有四个步骤:函数

一、  初始化Looperoop

二、  绑定handler到CustomThread实例的Looper对象布局

三、  定义处理消息的方法ui

四、  启动消息循环this

下面咱们以这个例子为线索,深刻Android源代码,说明Android Framework是如何创建消息循环,并对消息进行分发的。

一、  初始化Looper : Looper.prepare()

Looper.java

private static final ThreadLocal sThreadLocal = new ThreadLocal();
public static final void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper());
}

一个线程在调用Looper的静态方法prepare()时,这个线程会新建一个Looper对象,并放入到线程的局部变量中,而这个变量是不和其余线程共享的(关于ThreadLocal的介绍)。下面咱们看看Looper()这个构造函数:

Looper.java

final MessageQueue mQueue;
private Looper() {
        mQueue = new MessageQueue();
        mRun = true;
        mThread = Thread.currentThread();
    }

能够看到在Looper的构造函数中,建立了一个消息队列对象mQueue,此时,调用Looper. prepare()的线程就创建起一个消息循环的对象(此时还没开始进行消息循环)。

二、  绑定handler到CustomThread实例的Looper对象 : mHandler= new Handler()

Handler.java

final MessageQueue mQueue;
 final Looper mLooper;
public Handler() {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = null;
}

Handler经过mLooper = Looper.myLooper();绑定到线程的局部变量Looper上去,同时Handler经过mQueue =mLooper.mQueue;得到线程的消息队列。此时,Handler就绑定到建立此Handler对象的线程的消息队列上了。

三、定义处理消息的方法:Override public void handleMessage (Message msg){}

     子类须要覆盖这个方法,实现接受到消息后的处理方法。

四、启动消息循环 : Looper.loop()

      全部准备工做都准备好了,是时候启动消息循环了!Looper的静态方法loop()实现了消息循环。

Looper.java

public static final void loop() {
        Looper me = myLooper();
        MessageQueue queue = me.mQueue;
        
        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();
        
        while (true) {
            Message msg = queue.next(); // might block
            //if (!me.mRun) {
            //    break;
            //}
            if (msg != null) {
                if (msg.target == null) {
                    // No target is a magic identifier for the quit message.
                    return;
                }
                if (me.mLogging!= null) me.mLogging.println(
                        ">>>>> Dispatching to " + msg.target + " "
                        + msg.callback + ": " + msg.what
                        );
                msg.target.dispatchMessage(msg);
                if (me.mLogging!= null) me.mLogging.println(
                        "<<<<< Finished to    " + msg.target + " "
                        + msg.callback);
                
                // Make sure that during the course of dispatching the
                // identity of the thread wasn't corrupted.
                final long newIdent = Binder.clearCallingIdentity();
                if (ident != newIdent) {
                    Log.wtf("Looper", "Thread identity changed from 0x"
                            + Long.toHexString(ident) + " to 0x"
                            + Long.toHexString(newIdent) + " while dispatching to "
                            + msg.target.getClass().getName() + " "
                            + msg.callback + " what=" + msg.what);
                }
                
                msg.recycle();
            }
        }
    }

while(true)体现了消息循环中的“循环“,Looper会在循环体中调用queue.next()获取消息队列中须要处理的下一条消息。当msg != null且msg.target != null时,调用msg.target.dispatchMessage(msg);分发消息,当分发完成后,调用msg.recycle();回收消息。

msg.target是一个handler对象,表示须要处理这个消息的handler对象。Handler的void dispatchMessage(Message msg)方法以下:

Handler.java

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
}

可见,当msg.callback== null 而且mCallback == null时,这个例子是由handleMessage(msg);处理消息,上面咱们说到子类覆盖这个方法能够实现消息的具体处理过程。

总结:从上面的分析过程可知,消息循环的核心是Looper,Looper持有消息队列MessageQueue对象,一个线程能够把Looper设为该线程的局部变量,这就至关于这个线程创建了一个对应的消息队列。Handler的做用就是封装发送消息和处理消息的过程,让其余线程只须要操做Handler就能够发消息给建立Handler的线程。由此能够知道,在上一篇《 Android异步处理一:使用Thread+Handler实现非UI线程更新UI界面》中,UI线程在建立的时候就创建了消息循环(在ActivityThread的public static final void main(String[] args)方法中实现),所以咱们能够在其余线程给UI线程的handler发送消息,达到更新UI的目的。

完整代码:

package com.xsjayz.looper;

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;

public class LooperThreadActivity extends Activity {

	private final int MSG_HELLO = 0;
	private Handler handler;
	private Button button;

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

		button = (Button) findViewById(R.id.send_btn);

		new CustomThread().start();

		// 点击按钮时发送消息
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String str = "hello";
				Log.d("Test", "MainThread is ready to send msg0000000000:"
						+ str);
				// 发送消息到CustomThread实例
				handler.obtainMessage(MSG_HELLO, str).sendToTarget();
			}
		});
	}

	/**
	 * 创建消息循环的步骤
	 */
	class CustomThread extends Thread {
		@Override
		public void run() {
			// 一、初始化Looper
			Looper.prepare();
			// 二、绑定handler到CustomThread实例的Looper对象
			handler = new Handler() {
				// 三、定义处理消息的方法
				public void handleMessage(Message msg) {
					switch (msg.what) {
					case MSG_HELLO:
						Log.d("Test", "CustomThread receive msg1111111111:"
								+ (String) msg.obj);
					}
				}
			};
			// 四、启动消息循环
			Looper.loop();
		}
	}
}

布局文件:main.xml

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/send_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/send_msg" >
    </Button>

</LinearLayout>
相关文章
相关标签/搜索