Android消息机制-Handler,Message,Mess
Android的消息是怎样传的?Handler为什么要这么用?
一个简单的例子
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.lang.ref.WeakReference;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity>";
private final MyHandler handler=new MyHandler(MainActivity.this);
private final MyRunable myRunable=new MyRunable(MainActivity.this);
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.textView);
handler.postDelayed(myRunable,30000);
}
/**
* 静态内部类,防止对外部类的引用
*/
private static class MyHandler extends Handler{
private final WeakReference<MainActivity> mainActivityWeakReference;
public MyHandler(MainActivity mainActivity) {
this.mainActivityWeakReference = new WeakReference<MainActivity>(mainActivity);
}
@Override
public void handleMessage(Message msg) {
MainActivity mainActivity=mainActivityWeakReference.get();
if (mainActivity!=null){
Log.d(TAG, "handleMessage: !!!!!!!!!");
}else {
Log.d(TAG, "run: mainActivity already destroy!");
}
}
}
/**
* 静态内部类,防止对外部类的引用造成内存泄露
*/
private static class MyRunable implements Runnable {
private final WeakReference<MainActivity> mainActivityWeakReference;
public MyRunable(MainActivity main) {
this.mainActivityWeakReference = new WeakReference<MainActivity>(main);
}
@Override
public void run() {
MainActivity mainActivity=mainActivityWeakReference.get();
if (mainActivity!=null){
Log.d(TAG, "run: !!!!!!!!!!!!!!!!!!!");
}else {
Log.d(TAG, "run: mainActivity already destroy!");
}
}
}
}
Handler 怎么发消息的?
留给开发者的接口:
post方式:
post
sendMessage方式:
- sendMessage(Message msg)
- sendEmptyMessage(int what)
- sendEmptyMessageDelayed(int what, long delayMillis)
- sendMessageDelayed(Message msg, long delayMillis)
- sendMessageAtTime(Message msg, long uptimeMillis)
两种方式发送的最终对象都是Message,发送的最终方式都是sendMessageAtTime(Message msg, long uptimeMillis)或sendMessageAtFrontOfQueue(Message msg),两个通用的接口变化出不同情况的接口,这样做的好处就是方便开发者灵活调用吧。很多类的构造方法也是如此
那么,继续,看sendMessageAtTime
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue; //获取messageQueue,就是消息队列
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);
}
消息队列不为空,就调用enqueueMessage()方法,但是mQueue从哪儿来的?
这里可以查看Handler的构造方法:
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 that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
Handler的构造方法我分为两类,一类是要传Looper的,一类的不传Looper的,这里是不传Looper的,不传Looper的最终都会调用上述方法,也就是用的当前线程的Looper,一般是使用的时候都是主线程的Looper,比如前面的例子就是不传Looper得到的handler。具体Looper.myLooper()怎么获取的,待会在看。一个Looper拥有一个消息队列,所以mLooper.mQueue就给Handler的mQueue赋值了
继续 看sendMessageAtFrontOfQueue(Message msg)
public final boolean sendMessageAtFrontOfQueue(Message msg) {
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, 0);
}
除了最终调用enqueueMessage()传入的第三个参数,方法块几乎一摸一样,可以看出0就是将消息放在消息队列的最前面了
继续 终于羊肠小道了
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
这里可以先看下Message类,个人认为,Message就是个消息的载体,像货箱,大货箱里面又有很多位置,比如what,arg1,arg2放int数据,obj放引用数据,位置不够还可以用Bundle; public static Message obtain()方法可以快速获取一个实例化的Message;最后有个重要的成员就是target,就是指定最终处理它的Handler对象。enqueueMessage()方法给msg的target为Handler自己,从而得出message由Handler发送,也由同一个Handler处理。
MessageQueue是如果入队的?查看enqueueMessage(Message msg, long when)
boolean enqueueMessage(Message msg, long when) {
// 如果处理它的Handler为空,当然选择抛异常
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
// 如果msg已经标记被使用了,当然选择抛异常 ,你发个已经被用的msg来干嘛
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
// 在同步的情况下,检查此队列所在的线程(比如主线程)有没有dead,dead的话回收msg,返回false,退出此方法
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正在使用
msg.markInUse();
// 执行时间,队列是以时间顺序放的,0代表放队列的最前面,当然越前面就越先执行
msg.when = when;
// 当前待执行的Message,应该是从队列跑出来的
Message p = mMessages;
// 需不需要唤醒
boolean needWake;
// 如果当前待执行的Message为空,或者传入的msg执行时间为现在,或者执行时间还要比待执行Message的执行时间还要提前,那么当然是优先执行传入的msg啦
if (p == null || when == 0 || when < p.when) {
// 指定下一要执行的msg
msg.next = p;
// 替换当前待执行的Message为新传入的msg
mMessages = msg;
// New head, wake up the event queue if blocked. 保证唤醒队列,可以动了
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.
// 设置唤醒状态 = 当前唤醒 并且 当前待执行的Message为空 并且 新msg为异步msg
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;
}
新msg入队过程
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;
}
首先从头开始遍历队列
遍历队列
在遍历过程的每一步判断,如果新msg的执行时间比p的执行时间提前,则停止遍历,插入新msg
image.png image.png在enqueueMessage中首先判断,如果当前的消息队列为空,或者新添加的消息的执行时间when是0,或者新添加的消息的执行时间比消息队列头的消息的执行时间还早,就把消息添加到消息队列头(消息队列按时间排序),否则就要找到合适的位置将当前消息添加到消息队列。
主线程的Looper是在哪儿启动消息循环的?
从Android程序的Main方法看,它就在Android.App.MainThread.java类里
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
可以看到调用了Looper.prepareMainLooper(),然后实例化了一个sMainThreadHandler,然后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));
}
sThreadLocal 设置了一个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就是从sThreadLocal得到的,可以知道这里用了ThreadLocal类,那么ThreadLocal是干嘛的呢?
ThreadLocal干嘛的?
这里采用该作者的讲解,理解Java中的ThreadLocal
1.ThreadLocal是一个关于创建线程局部变量的类。
2.通常情况下,我们创建的变量是可以被任何一个线程访问并修改的。而使用ThreadLocal创建的变量只能被当前线程访问,其他线程则无法访问和修改。
3.正如Android的Looper,设计出来就是一个线程维护一个Looper,使用ThreadLocal保证了一个线程最多一个Looper,其实分析下ThreadLocal相关的方法,就知道ThreadLocal的值是放入了当前线程的一个ThreadLocalMap实例中,所以只能在本线程中访问,其他线程无法访问。
Looper怎样循环的?
前面的代码可以知道,main方法里,创建了主线程的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;
// 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();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
if (logging != null) {
logging.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(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.recycleUnchecked();
}
}
就是不断地从messageQueue中取得新消息,如果消息不为空就调用message地target也就是处理它的Handler处理它,为空就退出循环。queue.next()可能会阻塞,查了查资料,两种情况下线程会进入等待状态,两种情况,一是当消息队列中没有消息时,它会使线程进入等待状态;二是消息队列中有消息,但是消息指定了执行的时间,而现在还没有到这个时间,线程也会进入等待状态。消息队列中的消息是按时间先后来排序的,后面我们在分析消息的发送时会看到。
我觉主线程的消息队列随时都有消息,很少有空闲的时候,因为应用启动后,界面不断刷新,那些控件的触摸事件等等各种各样的事件都需要处理,也许都添加进了主线程的事件队列(这个有待验证,我推测是这样的),那这样,主线程的任务也太多了吧。