🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
ActivityManagerService也是由SystemServer创建的。假设通过startActivit来启动一个新的Activity,而这个Activity附属于一个还未启动的进程,那么这个进程该如何启动呢?先来看看ActivityManagerService中的startProcessLocked函数,代码如下所示: **ActivityManagerService.java** ~~~ private final void startProcessLocked(ProcessRecordapp, String hostingType, String hostingNameStr){ ......//这个ActivityManagerService类很复杂,有14657行!!! if("1".equals(SystemProperties.get("debug.checkjni"))) { debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; } if("1".equals(SystemProperties.get("debug.assert"))) { debugFlags |= Zygote.DEBUG_ENABLE_ASSERT; } //这个Process类是Android提供的,并非JDK中的Process类 intpid = Process.start("android.app.ActivityThread", mSimpleProcessManagement ?app.processName : null, uid, uid, gids, debugFlags, null); ...... } ~~~ 接着来看看Process的start函数,这个Process类是android.os.Process,它的代码在Process.java中,代码如下所示: **Process.java** ~~~ public static final int start(final StringprocessClass,final String niceName, int uid, int gid, int[] gids,intdebugFlags,String[] zygoteArgs) { //注意,processClass的值是"android.app.ActivityThread"。 if(supportsProcesses()) { try { //调用startViaZygote。 return startViaZygote(processClass, niceName, uid, gid, gids, debugFlags,zygoteArgs); } } } ~~~ **Process.java::startViaZygote()** ~~~ private static int startViaZygote(final StringprocessClass, final String niceName,final int uid, finalint gid,final int[] gids, intdebugFlags,String[] extraArgs) throws ZygoteStartFailedEx { int pid; ......//一些参数处理,最后调用zygoteSendArgsAndGetPid函数。 argsForZygote.add("--runtime-init");//这个参数很重要 argsForZygote.add("--setuid=" +uid); argsForZygote.add("--setgid=" + gid); pid =zygoteSendArgsAndGetPid(argsForZygote); return pid; } ~~~ **Process.java::zygoteSendArgsAndGetPid()** ~~~ private static intzygoteSendArgsAndGetPid(ArrayList<String> args) throwsZygoteStartFailedEx { intpid; // openZygoteSocketIfNeeded?是不是打开了和Zygote通信的Socket? openZygoteSocketIfNeeded(); try { //把请求的参数发到Zygote。 sZygoteWriter.write(Integer.toString(args.size())); sZygoteWriter.newLine(); sZygoteWriter.write(arg); sZygoteWriter.newLine(); } //读取Zygote处理完的结果,便得知是某个进程的pid! sZygoteWriter.flush(); pid= sZygoteInputStream.readInt(); return pid; } ~~~ **Process.java** ~~~ private static void openZygoteSocketIfNeeded()throws ZygoteStartFailedEx { try { sZygoteSocket = new LocalSocket();//果真如此!! //连接Zygote sZygoteSocket.connect(new LocalSocketAddress(ZYGOTE_SOCKET, LocalSocketAddress.Namespace.RESERVED)); sZygoteInputStream = newDataInputStream(sZygoteSocket.getInputStream()); sZygoteWriter = new BufferedWriter( new OutputStreamWriter( sZygoteSocket.getOutputStream()),256); } } } } ~~~ 好了,ActivityManagerService终于向Zygote发送请求了。请求的参数中有一个字符串,它的值是“android.app.ActivityThread”。现在该回到Zygote处理请求那块去看看了。 >[info]**注意**:由于ActivityManagerService驻留于SystemServer进程中,所以正是SS向Zygote发送了消息。