導(dǎo)讀
- 移動(dòng)開發(fā)知識(shí)體系總章(Java基礎(chǔ)、Android、Flutter)
- Android Handler消息機(jī)制 、 Android中為什么主線程不會(huì)因?yàn)長(zhǎng)ooper.loop里的無(wú)限循環(huán)ANR?
通過(guò)前面的學(xué)習(xí)(復(fù)習(xí))我們知道ActivityThread其實(shí)不是一個(gè)Thread,而是一個(gè)final類型的Java類,并且擁有main(String[] args) 方法。Android原生以Java語(yǔ)言為基礎(chǔ),Java的JVM啟動(dòng)的入口就是main(String[] args)。
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// Install selective syscall interception
AndroidOs.install();
// 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();
// 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();
// 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");
}
以上為main方法中的全部代碼,我們關(guān)注以下幾點(diǎn):
- Looper.prepareMainLooper();
- Looper.loop();
- thread.attach(false, startSeq);
- thread.getHandler();
Looper.prepareMainLooper();
主程序Looper的初始化工作
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
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));
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
可以看到new Looper的時(shí)候傳了false
Looper.loop();
1.Looper就是字面意思(輪訓(xùn)器),在loop方法中無(wú)限循環(huán)的去MessageQueue(消息隊(duì)列)中讀取消息。
- MessageQueue則通過(guò)next方法無(wú)限循環(huán)的進(jìn)行消息出隊(duì),無(wú)消息時(shí)則會(huì)進(jìn)入睡眠
執(zhí)行thread.attach(false, startSeq);
通過(guò)thread.attach(false, startSeq);把ActivityThread 和主線程進(jìn)行綁定。