android.app.ActivityManager
ActivityManager负责ActivityThread的创建,Activity生命周期的维护
android.app.ActivityThread
该类中的main方法是Android应用的入口,每个apk中都包含一个且仅有一个ActivityThread类,并作为应用的主线程类。ActivityThread类管理主线程(UI线程)的执行,负责调度和运行应用中的activity,广播,以及其他操作。
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(); // //为当前线程(主线程)创建一个Looper对象
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler(); //为当前线程设置Handler
}
AsyncTask.init();
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop(); // 执行从消息队列中获取Message,并调用Handler进行处理的无限循环;所有和主线程相关的消息处理都在该方法中执行
throw new RuntimeException("Main thread loop unexpectedly exited");
}
1、可以看出里面方法调用了Looper.prepareMainLooper(), 该方法创建了一个Looper实例,且Looper构造方法创建了一个MessageQueue,由于Looper.prepareLooper()只能调用一次,因此,一个线程只存在一个Looper和一个MessageQueue
2、创建好Looper后,就调用了Looper.loop()方法,该方法会让当前线程进入无线循环状态,并不断从MessageQueue中获取msg,如果msg不为空,就执行msg.target.dispatchMessage(msg)方法(该target其实就是Handler对象),dispatchMessage(msg)方法最终执行Callback的handleMessage(msg)方法,否则等待监听
3、Handler的构造方法会首先获取到当前线程中保存的Looper实例,然后与Looper中的MessageQueue相关联。Handler的sendMessage方法会给msg的target赋值本身,然后调用将msg加入消息队列的方法queue.enqueueMessage(msg, uptimeMillis)
4、handler在主线程new出来的,那就是主线程;handler在子线程,如果要刷新UI,那么得new Handler(Looper.getMainLooper());子线程的handler必须要手动调用如下代码,否则报异常:
Looper.prepare();
Handler handler = new Handler();
Looper.loop();