我们都知道APP是运行在进程里的,当我们程序运行的时候,是以Zygote 进程作为模板(可以理解为继承,感兴趣可以搜“Zygote“)运行的,我们APP运行之前Zygote已经init一些Classes、resources、openGL 等等。
Android是支持多进程的,每个进程的内存使用限制一般为24MB的内存,一般情况下,简单的APP是运行在系统默认进程中,该进程名称就为应用的包名,但是多少的APP是运行在几个进程中的,可以通过android:process指定不同的进程,例如:
android:process=":process.test"
进程里面有运行的main线程,Looper、MessageQueue,Handler一直通过Looper.loop()不停的循环MessageQueue里的Message,这就解决不同线程中的通信问题。这个是谷歌封装好了的。
这里有必要特别提一下IntentService,这个被指为:用完自动销毁,不需要开发者自己再调用onDestroy(),IntentService是继承Service,并且其中有HandlerThread,HandlerThread 继承 Thread,本质也是一个Thread,具体知识自行搜索。
ZygoteInit里面有个方法invokeStaticMain(),通过反射机制调用ActivityThread.main方法,具体代码如下:
static void invokeStaticMain(ClassLoader loader,
String className, String[] argv)
throws ZygoteInit.MethodAndArgsCaller {
Class<?> cl;
try {
cl = loader.loadClass(className);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,
ex);
}
Method m;
try {
m = cl.getMethod("main", new Class[] { String[].class });
} catch (NoSuchMethodException ex) {
throw new RuntimeException(
"Missing static main on " + className, ex);
} catch (SecurityException ex) {
throw new RuntimeException(
"Problem getting static main on " + className, ex);
}
int modifiers = m.getModifiers();
if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
throw new RuntimeException(
"Main method is not public and static on " + className);
}
/*
* This throw gets caught in ZygoteInit.main(), which responds
* by invoking the exception's run() method. This arrangement
* clears up all the stack frames that were required in setting
* up the process.
*/
throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}
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());
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
这就是我们常说的主线程的创建过程,然后就是ActivityManagerService(ActivityManagerService简要分析),ActivityManagerService是个比较厉害的东西,其实现了IBinder接口,故可以进行进程间通信,ActivityManagerService主要负责管理Activity相关的所有东西,比如生命周期,Activity恢复之类的。