Handler机制是Android开发中最常见的机制,可以说贯穿整个Android,在探究Handler机制原理之前,我们先来捋一下用法
1.handler.post(Runnable)
2.handler.postdelayed(Runnable,int)
3.sendMessage(Message)
4.sendDelayMessage(Message,int)
从形式上就可以看出,第一种用法和第二种用法其实是一样的,只不过一个立即发送一个延迟发送而已,同理三四也是一样
我们先探究handler.post,post具体用法是
handler = new Handler();
hander.post(new runnable(){run(//具体逻辑){}});
首先我们找到Handler源码
public Handler() {
this(null, false);
}
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 = new Handler();时,实际上传入了两个参数进入Handler,一个是null,另一个是false
callback是一个接口,里面只有一个方法
public interface Callback {
public boolean handleMessage(Message msg);
}
这里传入的是null,暂且放下不谈。这个函数主要过程是初始化Handler里的变量mLooper,mQueue,mCallback以及mAsynchronous
首先mLooper = Looper.myLooper();从这里拿到一个looper,为什么这里会拿到一个looper对象?从这里就要引出ActivityThread.main方法
一个app启动开始,最先调用的方法是ActivityThread.main方法,如同java里的main方法一样,这个方法是程序的入口,那么这个方法到底干了什么
public static void main(String[] args) {
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());
Security.addProvider(new AndroidKeyStoreProvider());
// 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"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
多余的东西我们不看,我们只看Looper.prepareMainLooper();以及Looper.loop();
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
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.get()去查找looper,如果发现线程中以及有looper了就抛出异常,Only one Looper may be created per thread每一个线程中只能有一个loop
这里我们是程序第一次启动,当然没有looper,于是接下来调用new Looper创建一个looper
private Looper(