An explanation of the Android phone process startup process

Source: Internet
Author: User

Before resolving a boot search network slow problem, found that because the phone process up and then will be actively connected to rild, so to a certain extent, the phone process startup time will affect the speed of network status registration. When the phone process is properly advanced, you can advance the network registration time a little earlier so that the signal in the status bar is displayed in advance. So, how did the phone process start as one of the core processes of the system in Android?

RIL operating mechanism please refer to: http://blog.csdn.net/jason_wzn/article/details/53232022

Telephony is the first to create PhoneFactory objects, direct search for the source code, you can see that at the PhoneGlobals.java time of creation, the telephony will be called PhoneFactory to initialize the operation:

    /** * Global State for the telephony subsystem when running in the primary * phone process. */     Public  class phoneglobals extends contextwrapper {         Public void onCreate() {LOG.V (Log_tag,"[Email protected]_svc:phoneapp oncrate");//CallManager is empty            if(MCM = =NULL) {//Initialize the Telephony frameworkPhonefactory.makedefaultphones ( This);//Create CallManager instancesMCM = Callmanager.getinstance (); for(Phone phone:PhoneFactory.getPhones ())                {Mcm.registerphone (phone);    }                ....            } }

So, PhoneGlobals where was it created? Searching the code again, you can see that there is a file in the same file directory PhoneApp.java :

       @Override         Public void onCreate() {LOG.D ("Phoneapp","OnCreate");if(Userhandle.myuserid () = =0) {//Create Phoneglobals instancesMphoneglobals =NewPhoneglobals ( This);                Mphoneglobals.oncreate (); Mtelephonyglobals =NewTelephonyglobals ( This);            Mtelephonyglobals.oncreate (); }Else{LOG.D ("Phoneapp","Phone app is created as UserID not 0, there ' no Phoneapp () Instance"); }            ....        }

So, PhoneApp when was this class created? We know that every Android app has one Application corresponding to it, which is created during the app launch, but searches all of the source code here and cannot see where it was PhoneApp created. Really can't think out, find the next Niang, only to find the real start phone process place.

Open the source path where the phone process is located: /android/applications/sources/services/Telephony/ , view the files that the app corresponds to AndroidManefest.xml :

    <Manifest xmlns:android="Http://schemas.android.com/apk/res/android"            XMLNS:ANDROIDPRV="Http://schemas.android.com/apk/prv/res/android"             Package="Com.android.phone"            Android:versioncode="1"            Android:versionname="1.0.0"            Coreapp="true"            Android:shareduserid="Android.uid.phone"            Android:shareduserlabel="@string/phoneapplabel">.....<Application Android:name="Phoneapp"            android:persistent="true"            android:hardwareaccelerated="true"            Android:label="@string/phoneapplabel"            Android:icon="@mipmap/ic_launcher_phone"            Android:allowbackup="false"            Android:supportsrtl="true"            android:usescleartexttraffic="true"            Android:defaulttodeviceprotectedstorage="true"            Android:directbootaware="true">....</Application>    </manifest>

applicationbelow the label, you can see android:persistent="true" the value of this property and see how the official documentation explains it:

Android:persistent

Whether or not the application should remain running @ all times-' true ' if it should, and ' false ' if not. The default value is "false". Applications should not normally set this flag; Persistence mode is a intended only for certain system applications.

This shows that the phone application is the system resident process, once it has been up and running, will not be killed. For such a resident process, ActivityManagerService (hereinafter referred to as AMS) will be special treatment. SystemServerafter the core service of the system is initialized, it invokes the functions of AMS systemReady(Runnable r) :

     Public void Systemready(FinalRunnable goingcallback) {synchronized( This) {//Only start up encryption-aware persistent apps; once user is                //Unlocked we ' ll come back around and start unaware apps                //It is here that Phoneapp was created! Startpersistentapps (Packagemanager.match_direct_boot_aware);//Start up initial activity.Mbooting =true;//Enable home activity for system user, so that the system can always boot                if(Usermanager.issplitsystemuser ()) {ComponentName CName =NewComponentName (Mcontext, Systemuserhomeactivity.class);Try{Appglobals.getpackagemanager (). setcomponentenabledsetting (CName, P Ackagemanager.component_enabled_state_enabled,0, Userhandle.user_system); }Catch(RemoteException e) {ThrowE.rethrowasruntimeexception (); }} starthomeactivitylocked (Currentuserid,"Systemready"); }    }

Start all PackageManager.MATCH_DIRECT_BOOT_AWARE flags for true the app:

    Private void Startpersistentapps(intMatchflags) {synchronized( This) {Try{//Get all resident application information for the system                FinalList<applicationinfo> apps = Appglobals.getpackagemanager (). Getpersistentapplications (STOCK_ Pm_flags | matchflags). GetList (); for(ApplicationInfo App:apps) {if(!"Android". Equals (App.packagename)) {//Load ApplicationAddapplocked (App,false,NULL / * ABI override * /); }                }            }Catch(RemoteException ex) {            }        }    }//Add the application process to the LRU list and create the process    FinalProcessrecord addapplocked (applicationinfo info,BooleanIsolated, String abioverride) {Processrecord app;if(!isolated) {app = getprocessrecordlocked (Info.processname, Info.uid,true); }Else{app =NULL; }if(App = =NULL) {app = newprocessrecordlocked (info,NULL, isolated,0); Updatelruprocesslocked (App,false,NULL);        Updateoomadjlocked (); }        ....if((Info.flags & persistent_mask) = = Persistent_mask) {app.persistent =true;        App.maxadj = Processlist.persistent_proc_adj; }//Start the process. It'll either succeed and return a result containing        //The PID of the new process, or else throw a runtimeexception.        BooleanIsactivityprocess = (EntryPoint = =NULL);if(EntryPoint = =NULL) EntryPoint ="Android.app.ActivityThread";//Start the application        if(App.thread = =NULL&& Mpersistentstartingprocesses.indexof (APP) <0) {Mpersistentstartingprocesses.add (APP); Startprocesslocked (App,"added Application", App.processname, Abioverride,NULL / * entrypoint * /,NULL / * Entrypointargs * /); }returnApp }

Prepare to create an app process:

Private final void startprocesslocked (Processrecord app, String Hostingtype, String hostingnamestr, String Abio Verride, String entrypoint, string[] entrypointargs) {Process. ProcessstartresultStartresult = null;if (userid>0&& (bbcid>0&& UserID = = bbcid) && app. Info. Bbcseinfo!=null) {//START process Startresult = processes. Start(EntryPoint, App. ProcessName, UID, uid, Gids, DebugFlags, mountexternal, app. Info. Targetsdkversion, the app. Info. Bbcseinfo, the app. Info. Bbccategory, the app. Info. Accessinfo, Requiredabi, Instructionset, app. Info. DataDir, Mountknoxpoint, Entrypointargs);}esle{...} }

Called Process.start() to create a new process ActivityThread , the phone process is running in that process:

     Public Static FinalProcessstartresultStart(FinalString Processclass,FinalString Nicename,intUidintGidint[] Gids,intDebugFlags,intMountexternal,intTargetsdkversion, String Seinfo,intCategoryintAccessinfo, String Abi, String instructionset, String Appdatadir,BooleanMountknoxpoint, string[] zygoteargs) {Try{returnStartviazygote (Processclass, Nicename, uid, GID, Gids, DebugFlags, Mountexternal, Targetsdkversion, SeI        NFO, category, Accessinfo, Abi, Instructionset, Appdatadir, Mountknoxpoint, Zygoteargs); }Catch(Zygotestartfailedex ex) {LOG.E (Log_tag,"Starting VM process through Zygote failed");Throw NewRuntimeException ("Starting VM process through Zygote failed", ex); }    }

Send a message to the ZYGOTE socket port to request the creation of a new process:

 Private StaticProcessstartresultStartviazygote(FinalString Processclass,FinalString Nicename,Final intUidFinal intGidFinal int[] Gids,intDebugFlags,intMountexternal,intTargetsdkversion, String Seinfo,intCategoryintAccessinfo, String Abi, String instructionset, String Appdatadir,BooleanMountknoxpoint, string[] extraargs)throwsZygotestartfailedex {synchronized(process.class) {arraylist<string> argsforzygote =NewArraylist<string> ();//--runtime-args,--setuid=,--setgid=,            //And--setgroups= must go firstArgsforzygote.add ("--runtime-args"); Argsforzygote.add ("--setuid="+ UID); Argsforzygote.add ("--setgid="+ GID); ....if(Appdatadir! =NULL) {Argsforzygote.add ("--app-data-dir="+ Appdatadir); } ..... argsforzygote.add (Processclass);if(Extraargs! =NULL) { for(String Arg:extraargs)                {Argsforzygote.add (ARG); }            }//Send message to zygote socket port, request to create a new process            if(zygote.isenhancedzygoteaslrenabled) {....returnZygotesendargsandgetresult (openzygotesocketifneeded (ABI), argsforzygote);//End of isenhancedzygoteaslrenabled case}Else{//Original case                returnZygotesendargsandgetresult (openzygotesocketifneeded (ABI), argsforzygote); }        }    }

This way the phone process is created and the boot is complete. The whole process to look down, research Android system, source code is king, but to understand the system behind the design, or need to comb the basic concepts clearly, in order to better understand the logic behind the design of the system.

An explanation of the Android phone process startup process

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.