android中消息机制,Android消息机制

所谓的Android消息机制其实就是Handler机制,其主要的作用是将一个任务放到另外一个线程中去执行。一般来说用于网络请求之后更新UI的情况较多,但是这并不意味着Handler只能用于这种场景,为什么更新UI的时候要使用到Handler呢?因为Android规定只能在UI线程中访问UI,否则会报错!这个线程检查的操作是在ViewRootImpl的checkThread方法中去做的

void checkThread() {

if (mThread != Thread.currentThread()) {

throw new CalledFromWrongThreadException(

"Only the original thread that created a view hierarchy can touch its views.");

}

}

其中这个mThread就是UI线程。如果说没有Handler的话哪我们该怎么去刷新UI呢?

基本使用

private Handler handler = new Handler() {

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

switch (msg.what) {

case 0:

{

textView.setText("change");

}

}

}

};

...

new Thread(new Runnable() {

@Override

public void run() {

try {

Thread.sleep(5000);

} catch (InterruptedException e) {

e.printStackTrace();

}

handler.sendEmptyMessage(0);

}

}).start();

以上就是我们最常见的Handler最常见的写法,但是这样写存在一个很大的问题,那就是内存泄漏。在Java语言中,非静态内部类会持有外部类的一个隐试引用,这样就可能造成外部类无法被垃圾回收。而导致内存泄漏。很显然在这里Handler就是一个非静态内部类,它会持有Activity的应用导致Activity无法正常释放。

内存泄漏问题

上面说到Handler默认的使用方式岁会造成内存泄露,那么该如何去写呢?正确的写法应该是使用静态内部类的形式,但是如果只使用静态内部类的话handler调用activity中的方法又成了一个问题,因此使用弱引用来持有外部activity对象成为了很好的解决方案。代码如下:

final MyHandler handler=new MyHandler(this);

private static class MyHandler extends Handler {

//创建一个弱引用持有外部类的对象

private final WeakReference content;

private MyHandler(MainActivity content) {

this.content = new WeakReference(content);

}

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

MainActivity activity= content.get();

if (activity != null) {

switch (msg.what) {

case 0: {

activity.notifyUI();

}

}

}

}

}

@Override

protected void onDestroy() {

super.onDestroy();

handler.removeCallbacksAndMessages(this);

}

消息机制中的成员

Hander机制当中的主要成员有Handler、Looper、MessageQueue、Message这四个成员,当然Threadlocal也会存在一些踪迹,但是个人认为它并不属于Handler机制中的成员!

Handler

从名字的英文含义上你就能大概知道它是消息处理者,负责发送消息和处理消息。

Looper

是一个查询消息的循环结构,负责查询MessageQueue当中的消息

Message

这就是我们的消息,它能携带一个int数据和一个Object数据

MessageQueue

它是Message的一个集合

源码分析Handler机制的工作流程

631beb6d1e33

image.png

我们先从Handler发送消息开始,上面Demo中我们使用的是sendEmptyMessage方法,但其实我们还有一些了其他的send方法和post方法,但是这些方法最终都是要调用sendMessageAtTime具体代码如下

/**

* Enqueue a message into the message queue after all pending messages

* before the absolute time (in milliseconds) uptimeMillis.

* The time-base is {@link android.os.SystemClock#uptimeMillis}.

* Time spent in deep sleep will add an additional delay to execution.

* You will receive it in {@link #handleMessage}, in the thread attached

* to this handler.

*

* @param uptimeMillis The absolute time at which the message should be

* delivered, using the

* {@link android.os.SystemClock#uptimeMillis} time-base.

*

* @return Returns true if the message was successfully placed in to the

* message queue. Returns false on failure, usually because the

* looper processing the message queue is exiting. Note that a

* result of true does not mean the message will be processed -- if

* the looper is quit before the delivery time of the message

* occurs then the message will be dropped.

*/

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {

MessageQueue queue = mQueue;

if (queue == null) {

RuntimeException e = new RuntimeException(

this + " sendMessageAtTime() called with no mQueue");

Log.w("Looper", e.getMessage(), e);

return false;

}

return enqueueMessage(queue, msg, uptimeMillis);

}

在sendMessageAtTime有一个点就是mQueue这个变量,它是一个MessageQueue的对象。最终我们调用了enqueueMessage方法

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {

msg.target = this;

if (mAsynchronous) {

msg.setAsynchronous(true);

}

return queue.enqueueMessage(msg, uptimeMillis);

}

首先msg要绑定Handler,msg.target = this;这个好理解,一个Message对象只能由一个Handler来处理。然后

if (mAsynchronous) {

msg.setAsynchronous(true);

}

如果mAsynchronous为true表示该消息是异步的。最后一步是将消息交给我们的MessageQueue的enqueueMessage处理,代码如下:

boolean enqueueMessage(Message msg, long when) {

if (msg.target == null) {

throw new IllegalArgumentException("Message must have a target.");

}

if (msg.isInUse()) {

throw new IllegalStateException(msg + " This message is already in use.");

}

synchronized (this) {

if (mQuitting) {

IllegalStateException e = new IllegalStateException(

msg.target + " sending message to a Handler on a dead thread");

Log.w(TAG, e.getMessage(), e);

msg.recycle();

return false;

}

msg.markInUse();

msg.when = when;

Message p = mMessages;

boolean needWake;

if (p == null || when == 0 || when < p.when) {

// New head, wake up the event queue if blocked.

msg.next = p;

mMessages = msg;

needWake = mBlocked;

} else {

// Inserted within the middle of the queue. Usually we don't have to wake

// up the event queue unless there is a barrier at the head of the queue

// and the message is the earliest asynchronous message in the queue.

needWake = mBlocked && p.target == null && msg.isAsynchronous();

Message prev;

for (;;) {

prev = p;

p = p.next;

if (p == null || when < p.when) {

break;

}

if (needWake && p.isAsynchronous()) {

needWake = false;

}

}

msg.next = p; // invariant: p == prev.next

prev.next = msg;

}

// We can assume mPtr != 0 because mQuitting is false.

if (needWake) {

nativeWake(mPtr);

}

}

return true;

}

到这我们的Message对象就添加到MessageQueue当中了!到这里我们理解了Handler的send和post方法的实际作用就是将Message消息添加到MessageQueue之中,但是这一系列的操作之中我们并没有看见创建MessageQueue对象的过程,似乎在这之前它已经创建好了,于是我们想起了之前的一个变量叫mQueue,它是一个MessageQueue的对象

final MessageQueue mQueue;

那他是在哪得到的呢?我们看一下Handler的构造方法,以我们最常用的来看

/**

* Default constructor associates this handler with the {@link Looper} for the

* current thread.

*

* If this thread does not have a looper, this handler won't be able to receive messages

* so an exception is thrown.

*/

public Handler() {

this(null, false);

}

该方法调用了

/**

* Use the {@link Looper} for the current thread with the specified callback interface

* and set whether the handler should be asynchronous.

*

* Handlers are synchronous by default unless this constructor is used to make

* one that is strictly asynchronous.

*

* Asynchronous messages represent interrupts or events that do not require global ordering

* with respect to synchronous messages. Asynchronous messages are not subject to

* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.

*

* @param callback The callback interface in which to handle messages, or null.

* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for

* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.

*

* @hide

*/

public Handler(Callback callback, boolean async) {

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 " + Thread.currentThread()

+ " that has not called Looper.prepare()");

}

mQueue = mLooper.mQueue;

mCallback = callback;

mAsynchronous = async;

}

好了我们看到了mQueue实际上是通过mLooper.mQueue这获取到的。而mLooper又是通过

Looper.myLooper();

这个方法来获取到的,分析到这终于又出现了一个关键字Looper,那我们看一下myLooper这个方法

/**

* Return the Looper object associated with the current thread. Returns

* null if the calling thread is not associated with a Looper.

*/

public static @Nullable Looper myLooper() {

return sThreadLocal.get();

}

哈!一脸懵逼。但是大概可以知道Looper对象被存在了一个对象里面,看到了get方法我很容易想到它也许还有set方法,我们先来看一下这个sThreadLocal是什么?

static final ThreadLocal sThreadLocal = new ThreadLocal();

好了我们知道ThreadLocal这东西了,但是到这线索似乎断了set方法在哪里?这时候我忽然想到如果在子线程中使用Handler是一个什么样的场景!如果不先调用Looper.prepare()方法是会报错吧!问题的关键就在于这,我们看一下代码

/** Initialize the current thread as a looper.

* This gives you a chance to create handlers that then reference

* this looper, before actually starting the loop. Be sure to call

* {@link #loop()} after calling this method, and end it by calling

* {@link #quit()}.

*/

public static void prepare() {

prepare(true);

}

private static void prepare(boolean quitAllowed) {

if (sThreadLocal.get() != null) {

throw new RuntimeException("Only one Looper may be created per thread");

}

sThreadLocal.set(new Looper(quitAllowed));

}

sThreadLocal的set方法被我们找到了,并且new了一个Looper。由此可见我们的Looper也是存在ThreadLocal中的。Looper的构造方法如下所示

private Looper(boolean quitAllowed) {

mQueue = new MessageQueue(quitAllowed);

mThread = Thread.currentThread();

}

好了mQueue这个对象的由来算是讲清楚了,他就是一个MessageQueue对象!可以说Looper和MessageQueue是一一对应的,一个Looper对象中含有一个MessageQueue。ThreadLocal通过set方法将Looper存在其中,那么我们具体看一下set方法实现

/**

* Sets the current thread's copy of this thread-local variable

* to the specified value. Most subclasses will have no need to

* override this method, relying solely on the {@link #initialValue}

* method to set the values of thread-locals.

*

* @param value the value to be stored in the current thread's copy of

* this thread-local.

*/

public void set(T value) {

Thread t = Thread.currentThread();

ThreadLocalMap map = getMap(t);

if (map != null)

map.set(this, value);

else

createMap(t, value);

}

可以看到Looper对象最终被存储在了一个叫ThreadLocalMap的数据结构里面,createMap方法用于创建ThreadLcalMap对象,createMap方法中会new一个ThreadLocalMap对象并将这个对象赋给t的threadlocals属性

/**

* Create the map associated with a ThreadLocal. Overridden in

* InheritableThreadLocal.

*

* @param t the current thread

* @param firstValue value for the initial entry of the map

*/

void createMap(Thread t, T firstValue) {

t.threadLocals = new ThreadLocalMap(this, firstValue);

}

ThreadLocalMap个人认为是一个hash表,同样是的形式有些和HashMap类似,它同样存在自己的扩容机制,同样存在自己的hash函数。到这里我们明白了MessageQueue是存在Looper里面的,而Looper又是存在ThreadLocal里面的,Thread当中有且只有一个ThreadLocal.ThreadLocalMap对象,因此Thread、Looper和MessageQueue三者形成了一一对应的关系,然而Handler于他们没有一点关系,Handler只和Message对象成对应的关系,所以Thread、Looper、MessageQueue、Handler四者的关系是一个线程中只能有一个Looper和一个MessageQueue但是可以存在一个或者多个Handler。到这里他们之间的关系我们搞清楚了!另外我们也知道在调用了MessageQueue的enqueueMessage方法之后我们就把Message对象添加到了MessageQueue当中了,剩下的事情就是Message是如何被处理的,在子线程当中使用Handler的时候除了要先写Looper.prepare()之外,还要写Looper.loop()方法

/**

* Run the message queue in this thread. Be sure to call

* {@link #quit()} to end the loop.

*/

public static void loop() {

final Looper me = myLooper();

if (me == null) {

throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");

}

final MessageQueue queue = me.mQueue;

...

boolean slowDeliveryDetected = false;

for (;;) {

Message msg = queue.next(); // might block

if (msg == null) {

// No message indicates that the message queue is quitting.

return;

}

...

try {

msg.target.dispatchMessage(msg);

dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;

} finally {

if (traceTag != 0) {

Trace.traceEnd(traceTag);

}

}

...

msg.recycleUnchecked();

}

}

可以看到loop方法中有一个无限的for循环,在循环中通过queue.next()来便利Message,然后我们看到了这句代码

msg.target.dispatchMessage(msg);

这个target就是我们之前绑定的Handler,也就是说我们在这里调用了Handler的dispatchMessage()方法并且将msg作为参数传递了过去,我们看看dispatchMessage的代码

/**

* Handle system messages here.

*/

public void dispatchMessage(Message msg) {

if (msg.callback != null) {

handleCallback(msg);

} else {

if (mCallback != null) {

if (mCallback.handleMessage(msg)) {

return;

}

}

handleMessage(msg);

}

}

如果说msg的callback不为空调用handleCallback将消息交给子线程去处理,这种处理方式主要是对应了post(runable)这种形式发送消息的情况。另外就是调用handleMessage方法了,好了这个方法我们再熟悉不过了,到这里消息从MessageQueue中取出并交由Handler处理的过程也完成了。最后在loop方法中调用msg.recycleUnchecked(),到这Handler消息机制我们就算是分析完成了。那么Handler是这么实现跨线程通讯的呢?就是通过方法回调,和接口回调。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值