How to start a new process for Android?

Source: Internet
Author: User

We need start a new process when we tap application launcher or start a new service which is in a different process. this artical will describe how a new process is created but no matter whoever the caller is.

1. startprocesslocked in activitymanagerservice. Java
Ignore rest of the function and focus on below code.

 Int pid = process. Start ("android. App. activitythread", <br/> msimpleprocessmanagement? App. processname: NULL, uid, uid, <br/> gids, debugflags, null); <br/>

According to above code, we can find that another process created with a nice name "app. processname" or null where the first ARGs is the first class started by the new process.

Now, we look into the start function of the Process class.

2. startviazygote in process. Java

Argsforzygote. add ("-- runtime-init"); <br/> argsforzygote. add ("-- setuid =" + UID); <br/> argsforzygote. add ("-- setgid =" + GID); <br/> 
The first sentence means that we need to init runtime when create this process, the purpose of this initialization will be discussed later.
We shoshould know the communication between activitymanagerservice and zygote relies on socket, am writes the arguments of the new process into the buffer for zygote socket.
Then the starter's work is done, let's turn over into the zygote at looked at the other socket communication side.

3.
The zygote process will be in a loop in order to detect any connect into the zygote socket and fork the request process after being started by init deamon process, all this work is running in function runselectloopmode in zygoteinit. java and callrunonce function in zygoteconnection. java to fork new process.

4. runonce in zygoteconnection. Java
 
PID = zygote. forkandspecialize (parsedargs. uid, parsedargs. GID, <br/> parsedargs. gids, parsedargs. debugflags, rlimits); <br/> 
Above code forks a new process, it is very easy to understand and unnecessary to look.
 
If (pid = 0) {<br/> // In child <br/> handlechildproc (parsedargs, descriptors, newstderr ); <br/> // shocould never happen <br/> return true; <br/>}else {/* PID! = 0 */<br/> // in parent... PID of <0 means failure <br/> return handleparentproc (PID, descriptors, parsedargs); <br/>}

As we know, parent process and child process will execute the code simultaneously after fork operation, therefore, the parent process will get the real PID of child process and call handleparentproc method, meanwhile, the child process will get a zero PID value and call handlechildproc.
We ignore the handleparentproc in which there is nothing important but cleanup of parent process.

The belowing operations are in the new process.

5. handlechildproc in zygoteconnection. Java

Function handlechildproc will check if the process starter needs the runtime initialization which is set in step 2. here need to init runtime while every process is being created.

If (parsedargs. runtimeinit) {<br/> runtimeinit. zygoteinit (parsedargs. remainingargs); <br/>}< br/>
6. zygoteinit in runtimeinit. Java

Public static final void zygoteinit (string [] argv) <br/> throws zygoteinit. methodandargscaller {<br/> // todo: doing this here works, but it seems kind of arbitrary. find <br/> // a better place. the goal is to set it up for applications, but not <br/> // tools like AM. <br/> system. setout (New androidprintstream (log. info, "system. out "); <br/> system. seterr (New androidprintstream (log. warn, "System. Err "); </P> <p> commoninit (); <br/> zygoteinitnative (); </P> <p> int curarg = 0; <br/> for (/* curarg */; curarg <argv. length; curarg ++) {<br/> string Arg = argv [curarg]; </P> <p> If (Arg. equals ("--") {<br/> curarg ++; <br/> break; <br/>} else if (! Arg. startswith ("--") {<br/> break; <br/>} else if (Arg. startswith ("-- nice-name =") {<br/> string nicename = Arg. substring (Arg. indexof ('=') + 1); <br/> process. setargv0 (nicename); <br/>}</P> <p> If (curarg = argv. length) {<br/> slog. E (TAG, "missing classname argument to runtimeinit! "); <Br/> // Let the process exit <br/> return; <br/>}</P> <p> // remaining arguments are passed to the start class's static main </P> <p> string startclass = argv [curarg + +]; <br/> string [] startargs = new string [argv. length-curarg]; </P> <p> system. arraycopy (argv, curarg, startargs, 0, startargs. length); <br/> invokestaticmain (startclass, startargs); <br/>}< br/>
6.1 zygoteinitnative
This function is a native function which spawns a pool thread to detect binder IPCS. Its Prototype in JNI layer is underlying:

Static void com_android_internal_ OS _runtimeinit_zygoteinit (jnienv * ENV, jobject clazz) <br/>{< br/> gcurruntime-> onzygoteinit (); <br/>}< br/>

 

Gcurruntime is a global variable which is initialized when app_main starts. we can find this process in androidruntime constructor. so we confirm that the gcurruntime is an appruntime instance and class appruntime extends androidruntime. according to all the facts, we can conclude the onzygoteinit function belongs to class appruntime.
Virtual void onzygoteinit () <br/>{< br/> sp <processstate> proc = processstate: Self (); <br/> If (proc-> supportsprocesses ()) {<br/> logv ("app process: Starting thread pool. /n "); <br/> proc-> startthreadpool (); <br/>}< br/>
6.2 invokestaticmain

After creating process and corresponding pool thread for binder IPC, the last job here is to call the "Main" method of the process's first class. it shoshould be "android. app. activitythread "for am to start a new activity or service of different processes.
Activitythread instance is the main thread of the new process.

7. main method in activitythread. Java
Public static final void main (string [] ARGs) {<br/> samplingprofilerintegration. start (); </P> <p> process. setargv0 ("<pre-initialized>"); </P> <p> logoff. preparemainlooper (); <br/> If (smainthreadhandler = NULL) {<br/> smainthreadhandler = new handler (); <br/>}</P> <p> activitythread thread = new activitythread (); <br/> thread. attach (false); </P> <p> If (false) {<br/> logoff. mylogoff (). setmessageloggi Ng (New <br/> logprinter (log. debug, "activitythread"); <br/>}</P> <p> logoff. loop (); </P> <p> If (process. supportsprocesses () {<br/> throw new runtimeexception ("main thread loop unexpectedly exited"); <br/>}</P> <p> thread. detach (); <br/> string name = (thread. minitialapplication! = NULL) <br/>? Thread. minitialapplication. getpackagename () <br/>: "<Unknown>"; <br/> slog. I (TAG, "main thread of" + name + "is now exiting"); <br/>}< br/>
In abve code, we can not find any sentence create the new activity or service. Where is the operation hiding?

The implementation is very complicated, the above Code has a sentence "thread. Attach (false)" where all the stuff is hiding.

I will discuss how activity starts in later artical.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.