Handler线程消息处理逻辑

转载请注明出处:http://blog.csdn.net/droyon/article/details/20732979

我们可以开辟Handler用于消息的处理。我们可以使用主线程looper进行消息的收发loop。也可以使用我们新开辟的异步线程。

主线程:

mHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
			}
			
		};
异步线程:

HandlerThread hdThread = new HandlerThread("");
		hdThread.start();
		mHandler = new Handler(hdThread.getLooper());

以及自定义线程。(自定义线程变成Handler异步处理消息的线程,需要先在run里先执行Looper.prepare创建MesssageQueue,然后Looper.loop()让线程进入无线循环)

newThread newT = new newThread();
		newT.start();
		new Handler(newT.mLooper);

class newThread extends Thread{
		public Looper mLooper;
		public newThread(){}
		@Override
		public void run() {
			super.run();
			
			Looper.prepare();
			Looper newLoop = Looper.myLooper();
			mLooper = newLoop;
			Log.d("hlwang","onCreate looper ..... newLooper is:"+mLooper);
			mLooper.loop();
		}
		
	}

这篇文档主要就是阐述Handler是如何处理消息的。

普通线程:执行完run方法,线程结束。(走完了线程的生命周期)[新建状态(New)、就绪状态(Runnable):、运行状态(Running):阻塞状态(Blocked)]

Handler线程:线程启动会进入一个无线循环体之中,每循环一次,从其消息内部取出一个消息,回调其相应的消息处理函数。执行完一个消息继续循环,如果消息队列为空,则线程暂停,直到消息队列中有了新的消息。


handler需要解决的问题如下:

1、需要包括一个消息队列,队列中的消息一般采用排队机制,即先到的消息先处理。

2、线程执行while (true)进行无线循环,循环中从消息队列中取出消息,并根据消息的来源,回调其消息处理函数。

3、其他外部线程可以向本线程发送消息,插入到消息队列中,消息队列必须加锁,即消息队列不能同时进行读写操作。


我们看一下在Android中,如何对Handler的这三个问题进行实现。


1、首先创建消息队列。外部程序通过Handler向线程发送消息,消息经由Handler传递到MessageQueue对象中。

MessageQueue是通过Looper执行prepare方法创建的。任何线程都会执行start方法,启动run方法。无论是Activity主线程还是HandlerThread开启的线程。

而我们的Looper.prepare方法正是在run方法中执行的。如下:

HandlerThread.java(不要忘记执行Looper.loop方法)

public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }
我们进入到Loop.prepare方法内。
Looper.java

if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper());
其中ThreadLocal为线程本地存储。

ps:何为线程本地存储(可参阅java 编程思想)。对于类的内部静态变量,无论进程中的那个线程访问,其内容总是相同的,因为在编译器内部为static静态变量单独分配了空间。线程本地存储正好相反,不同的线程访问得到不同的结果。
言归正传,Looper是对应线程的,一个线程只能有一个Looper对象,这是Looper定义的。第一次调用Looper.prepare方法,会sThreadLocal.get,得到null,这个时候会new一个Looper对象,并且给sThreadLocal.set上。同一线程再次调用prepare就会throw RuntimeException。

接着往下看,new Looper中做了什么?

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

在Looper的构造方法里,创建了MessageQueue。

2、让线程进入无限循环

执行Looper.loop方法。此方法实现如下:

public static void loop() {
        Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        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 (msg != null) {
                if (msg.target == null) {
                    // No target is a magic identifier for the quit message.
                    return;
                }

                long wallStart = 0;
                long threadStart = 0;

                // This must be in a local variable, in case a UI event sets the logger
                Printer logging = me.mLogging;
                if (logging != null) {
                    logging.println(">>>>> Dispatching to " + msg.target + " " +
                            msg.callback + ": " + msg.what);
                    wallStart = SystemClock.currentTimeMicro();
                    threadStart = SystemClock.currentThreadTimeMicro();
                }

                msg.target.dispatchMessage(msg);

                if (logging != null) {
                    long wallTime = SystemClock.currentTimeMicro() - wallStart;
                    long threadTime = SystemClock.currentThreadTimeMicro() - threadStart;

                    logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
                    if (logging instanceof Profiler) {
                        ((Profiler) logging).profile(msg, wallStart, wallTime,
                                threadStart, threadTime);
                    }
                }

                // 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(TAG, "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();
            }
        }
    }

2.1、这里首先调用myLooper返回当前Looper对象,该函数内部仅仅通过线程本地存储sThreadLocal.get获取。

2.2、while(true)进入无限循环。

2.2.1、调用MessageQueue.next方法取出队列中的Message。如果当前队列为空,则当前线程会被挂起,也就是说,在next方法内部处理挂起线程的逻辑。

2.2.2、如果message不为null,则回调msg.target.dispatchMessage函数,此处的target也就是msg对应的Handler。

关于target,逻辑如下:

Handler在构造Message时:

public final Message obtainMessage()
    {
        return Message.obtain(this);
    }
public static Message obtain(Handler h) {
        Message m = obtain();
        m.target = h;

        return m;
    }

或者:

public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }

2.2.3、如果消息处理完成,会调用msg.recycle方法回收该Message对象占用的系统资源。因为Message类内部使用了一个数据池保存Message对象,从而避免了不停的创建和删除Message类对象。因此,每次处理完该Message,需要将Message对象表明为空闲状态,以便使该Message对象可以重用。

3、消息队列采用了排队的方式对消息进行处理,即先到的消息先处理,但如果消息本身指定了被处理的时刻,则必须等到该时刻才能处理。消息在MessageQueue中使用Message表示,对列中消息以链表的结构进行保存。Message中next变量指向下一个消息。

MessageQueue中有两个主要的函数,“取出消息” next方法,“增加消息”enquenceMessage方法。

next方法内部流程分三步:

final Message next() {
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;

        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            nativePollOnce(mPtr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                final Message msg = mMessages;
                if (msg != null) {
                    final long when = msg.when;
                    if (now >= when) {
                        mBlocked = false;
                        mMessages = msg.next;
                        msg.next = null;
                        if (false) Log.v("MessageQueue", "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    } else {
                        nextPollTimeoutMillis = (int) Math.min(when - now, Integer.MAX_VALUE);
                    }
                } else {
                    nextPollTimeoutMillis = -1;
                }

                // If first time, then get the number of idlers to run.
                if (pendingIdleHandlerCount < 0) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount == 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf("MessageQueue", "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

3.1、调用nativePollOnce方法

nativePollOnce(mPtr, nextPollTimeoutMillis);
这是一个jni函数,其作用是从消息队列中取出一个消息。MessageQueue类内部本身没有保存消息队列,真正的消息队列保存在jni实现的c代码中。也就是说C环境中创建了一个NativeMessageQueue数据对象,这既是nativePollOnce函数第一个参数的意义。

private int mPtr; // used by native code
mPtr是一个int型变量,在c中将会被强制转换为NativeMessageQueue对象,在C环境中,如果消息队列中没有消息,则当前线程被挂起(wait),如果有消息,则c代码将该消息赋值给java环境中Message对象。

MessageQueue的jni代码在framework/base/core/jni/android_os_MessageQueue.cpp中。

3.2、接下来执行synchronized (this) 包含的代码段。this被用作趋消息和写消息的锁。在enqueueMessage方法中也使用了synchronized (this) 进行代码同步。

此段代码取出消息,判断该消息的执行时间是否到达,如果到了,就返回该消息,并将mMessage置空。否则,尝试获取下一个消息。

3.3、如果mMessage为null,说明c环境中的消息队列没有可执行消息。因此执行mPendingIdleHandler列表中的空闲回调函数。


添加消息代码:

enqueueMessage

final boolean enqueueMessage(Message msg, long when) {
        if (msg.isInUse()) {
            throw new AndroidRuntimeException(msg
                    + " This message is already in use.");
        }
        if (msg.target == null && !mQuitAllowed) {
            throw new RuntimeException("Main thread not allowed to quit");
        }
        final boolean needWake;
        synchronized (this) {
            if (mQuiting) {
                RuntimeException e = new RuntimeException(
                    msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                return false;
            } else if (msg.target == null) {
                mQuiting = true;
            }

            msg.when = when;
            //Log.d("MessageQueue", "Enqueing: " + msg);
            Message p = mMessages;
            if (p == null || when == 0 || when < p.when) {
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked; // new head, might need to wake up
            } else {
                Message prev = null;
                while (p != null && p.when <= when) {
                    prev = p;
                    p = p.next;
                }
                msg.next = prev.next;
                prev.next = msg;
                needWake = false; // still waiting on head, no need to wake up
            }
        }
        if (needWake) {
            nativeWake(mPtr);
        }
        return true;
    }

将参数msg赋值给mMessage。调用nativeWake(mPtr)。这是一个jni函数,其内部会将mMessage消息添加到C环境中的消息队列中,并且如果该线程处于wait状态,唤醒该线程。


Handler 的消息处理android实现,到此为止,我们在使用Handler时,一般实现其handleMessage方法。这是因为,在Message回调其target的dispatchMessage时会执行如下代码:

Handler.java

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


到此为止。如有不当之处,欢迎交流。



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hailushijie

您的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值