文章目录






一、主线程中的 Handler 与 Looper



Android 系统中 , 点击图标启动一个应用进程 , 就是从 Linux 的 Zygote 进程 fork 一个子进程 , 之后该子进程就会创建 ActivityThread , 执行其中的 main 函数 , 该 main 函数就是应用的主线程 ;



Android 的主线程在 ActivityThread 中创建并维护 , 在该类中的 main 函数 , 就是 Activity 中的主函数 ;

在该主函数中 , 调用 Looper.prepareMainLooper() 准备主线程 Looper ;

在最后的地方调用 Looper.loop() , 无限循环消息队列中的消息 ;

public final class ActivityThread extends ClientTransactionHandler {

public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

// 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>");

// 获取主线程 Handler 对应的 Looper
Looper.prepareMainLooper();

// Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
// It will be in the format "seq=114"
long startSeq = 0;
if (args != null) {
for (int i = args.length - 1; i >= 0; --i) {
if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
startSeq = Long.parseLong(
args[i].substring(PROC_START_SEQ_IDENT.length()));
}
}
}
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);

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");
}
}


源码参考 :​ ​​android/9.0.0_r8/xref/frameworks/base/core/java/android/app/ActivityThread.java​







二、Handler 原理简介



Handler 主要作用是 , 用于 线程间通信 ,

在线程 A A A 中创建 Handler , 在其它线程中使用 Handler 对象发送消息给 A A A 线程的 MessageQueue 消息队列 ,

线程 A A A 中的 Looper 不停地从 消息队列 ( MessageQueue ) 中取出 Message 消息 , 然后进行分发 ;



在线程 A A A 中使用 Handler , 首先要调用 Looper.prepare()方法 , 该方法的作用是准备轮询器 ,

Looper 创建后 , 会放在 ThreadLocal 中 , 这是线程的变量表 , 每个线程都有一个线程 ThreadLocal ,

使用线程 A A A 时 , 拿到 A A A 线程的 Looper , 在其它线程中调用 Handler 的 sendMessage 方法 ,

将消息传递给线程 A A A 中的 消息队列 ( MessageQueue ) 中 ,

Looper 中维护了一个 消息队列 ( MessageQueue ) , MessageQueue 封装在 Looper 中 ;



更多细节参考 :​ ​​【Android】Handler 机制 ( Handler | Message | Looper | MessageQueue )​