1, 为什么使用Handler?
Android的UI要求更新只能在UI线程,因为安卓是单线程模型。如果任意线程都可以更新UI的话,线程安全问题处理起来会相当麻烦复杂,就会出现页面错乱。所以就规定了Android的是单线程模型,只允许在UI线程更新UI操作。
也就是在Android中更新Ui必须在主线程,在子线程更新Ui会报子线程不能修改UI异常。
你想想安卓的页面一会被这个线程修改,一会被别的线程更改。用户体验就会很差,给别人一种不可控制的感觉。
作用:
线程间通讯,更新UI的机制,消息处理机制
Handler主要涉及4个类,分别是Handler、Looper、Message、MessageQueue。
1,消息的分发:Handler 发送和接收消息
2,消息的实体 :Message
3,消息队列的机制,怎么保证消息的有序存储和取出: MessageQueue
4,消息的线程间的通讯:Looper 消息的轮询机制,类似电机一直循环获取消息
面试提问:
1,Handler为什么会内存泄露:
长生命周期的引用短生命周期的对象,得不到释放内存;
ActivityThred长生命周期--->Loop-->MessageQueue-->message-->handler --》Activity 短生命周期对象
2,Message可以如何创建,哪种效果更好?
用Message.obtain()获取,缓存池,防止对象频繁创建、销毁造成内存抖动。
不用重复去创建 new Meaage ,
3、一个线程有几个Looper?可以有几个Handler?
一个线程只能有一个Looper,Looper.loop的时候,会形成死循环,此时即使有多个Looper也没有意义。那是怎么保证Looper的关系呢?通过ThreadLocal保证Looper和Thread的关系。
而一个线程可以有很多个Handler,只要在初始化的时候得到线程的Looper即可。
// sThreadLocal.get() will return null unless you've called prepare().
@UnsupportedAppUsage
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
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));
}
/**
* 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();
}
4、Looper.loop为什么不会导致主线程卡死
Looper 死循环,没消息会进行休眠不会卡死,调用 linux 底层的 epoll 机制实现
当App启动时,Zygote进程会fork新的进程,然后通过ActivityThread的main方法进入应用程序。在main方法中,会启动Looper.loop,而在loop之前,会通过thread.attach绑定ActivityManagerService。当系统有事件响应时,便会通知ActivityThread的mH进行处理。
public static void main(String[] args) {
········
Looper.prepareMainLooper();
········
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
········
Looper.loop();
}
// 用于处理AMS响应的事件
class H extends Handler {
public static final int BIND_APPLICATION = 110;
public static final int EXIT_APPLICATION = 111;
public static final int RECEIVER = 113;
public static final int CREATE_SERVICE = 114;
public static final int SERVICE_ARGS = 115;
public static final int STOP_SERVICE = 116;
········
}
源码分析 :
一 、创建Handler
handler.Callback的消息处理可以“覆盖”处理器自己的消息处理所以可以设置一个默认的消息处理注意:。返回值为true才“覆盖”默认的消息处理,如果都没有覆盖就是调用的handleMessage(MSG) ;方法啦这个方法就是你在处理程序重写的方法,消息方法一样。
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
Toast.makeText(HomeActivity.this, "msg", Toast.LENGTH_SHORT).show();
}
};
二 、创建 Message发送消息
Message message = Message.obtain();
message.obj = "自定义handler";
handler.sendMessage(message);
public final class Message implements Parcelable {
public int what;
public Object obj;
Handler target; //通过target 拿到Handler,从而调用handleMessage()方法
}
三、MessageQueue 添加消息到消息队列
创建 new Looper的时候就已经创建了MessageQueue
MessageQueue是在Looper类里拿的
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
handler.sendMessage 所有的消息都会走这个方法,添加到消息队列
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
synchronized (this) {
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
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;
}
四, Looper类
Looper类怎么来的呢?
看一下ActivityThread类 页面创建的就初始化了
public static void main(String[] args) {
//省略代码1
Looper.prepareMainLooper();
//省略代码2
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
//省略代码3
Looper.loop();
}
继续看Looper.prepareMainLooper();方法
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
里面有个 prepare(false);看这个:
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));
}
它new Looper跟进去
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
创建主线程时,会自动调用ActivityThread的1个静态的main();而main()内则会调用Looper.prepareMainLooper()为主线程生成1个Looper对象,同时也会生成其对应的MessageQueue对象。
看ActivityThread的main方法中省略代码3下面:
Looper.loop();
Looper调用了静态loop方法
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
首先判断了looper是否存在,不存在就会抛异常说没有looper,让你调用prepare方法创建Looper
public static void loop() {
//省略
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
这个死循环会取出Message有就取。没有就结束
msg.target.dispatchMessage(msg);
/**
* 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);
}
}
这个方法,把Message发个Handler了。
说明:
Looper持有 -->MessageQueue持有-->Message--Message.tager持有--handler持有-->activity 这样的关系链
所有Looper 死循环才有取出到Message
本来想写一篇详细的源码分析,由于能力和时间不够各位我尽力了