2024年5月27日发(作者:)
Android runtime:
调用过程以am broadcast为例:
1. Am发送广播进程
App_中main方法-
>调用中start方法((该方法中会在startReg中注册native方法)-
>进而调用eInit中的main方法(进而调用native中finishI
nit方法-
>app_中onStarted函数,进而调用中callMain方法,进而
调用中main方法-
>astIntent()…-
>startProcessLocked…会把消息post到ActivityThread的消息队列中…-
>ive()))->最后shut down VM
2. 另外一个进程(线程):
ZygoteInit中runForkMode/runSelectLoopMode进入一个无限循环在创建的socket接口上等待Ac
tivityManagerService请求
(acceptCommandPeer)
创建新进程forkAndSpecialize-
>handleChildProc->invokeStaticMain->throw MethodAndArgsCaller->invoke-
>->…-> Receiver ()-
>Receiver(会调用目标app,如果异常)->throw new
RuntimeException()…->htException()-
>ault().handleApplicationCrash()->ocess()
疑问:mParallelBroadcasts, mOrderedBroadcasts, BroadcastFilter
在android中,应用程序的入口是ActivityThead中的main函数,那么之后系统是
怎样为应用程序创建进程的呢?SystemService又是怎样创建的?答案是:zygote
zygote翻译成中文是受精卵的意思,名字比较奇怪、但是很有意思。在android
中,大部分的应用程序进程都是由zygote来创建的,为什么用大部分,因为还有
一些进程比如系统引导进程、init进程等不是有zygote创建的。相反,zygote还是
在init进程之后才被创建的。在android中提到zygote,主要两块,一个是C/C++
编写的zygote,主要用来为应用和SystemService fork进程的。一个是java编写的
zygote接口,负责为应用和service调用C/C++ zygote的接口执行fork,从而创建
VM进程。说明:在android中,service主要有NativeService和SystemService。
SystemService主要是指系统中service,比如,InputMethodService、
ActivityManagerService等。
zygote在android中主要有两个作用:
建立运行时环境并启动虚拟机,执行Init的main函
数,从而fork SystemService
("Init",
1
startSystemServer);
为应用程序创建DVM进程。
启动SystemServer:
我们来看看zygote是怎样创建SystemService进程的。
在../base/cmds/app_process/app_的主函数中,有这样一段代码,它执行了
(“Init”, startSystemServer); //runtime继承
自AndroidRuntime
也就是说,在主函数中,初始化了运行时环境,并且建立虚拟机,然后运行再
Init的main函数
再来看看Init的main中都做了哪些事情。在看
ZygoteInit之前,有必要先来看下相关的类,类图如下:
在ZygoteInit的main函数中,主要执行了:
registerZygoteSocket();//
登记
Listen
端口
startSystemServer();//
启动
SystemServer
startSystemServer()调用Zygote的native方法 forkSystemServer(); 到这里,java端的
Zygote的准备工作就结束了,接下来就交给C/C++端的Zygote来执行fork任务
了。来看下代码:
在 ../dalvik/vm/native/dalvik_system_Zygote.c 中
static void Dalvik_dalvik_system_Zygote_forkSystemServer(
const u4* args, JValue* pResult)
{
pid_t pid;
/*
调用
forkAndSpecializeCommon
,执行
fork */
pid = forkAndSpecializeCommon(args, true);
/*
检查
fork
后返回的进程
pid */
if (pid > 0) {
int status;


发布评论