Related articles
Android Deep understanding four components series
Preface
I used a long time to describe the startup process of the Android application (the root activity startup process), which we followed to analyze the service startup process. Before reading this article, please read Android deep four components (i) Application launch process (previous) and Android deep four components (a) Application launch process (POST) these two articles.
1.ContextImpl to Activitymanageservice call procedure
To start the service, we call the StartService method, which is implemented in Contextwrapper, as shown in the code below.
Frameworks/base/core/java/android/content/contextwrapper.java
publicclass ContextWrapper extends Context { Context mBase;... @Override publicstartService(Intent service) { return mBase.startService(service); }... }
The StartService method of Mbase is called in the StartService method, and what does the context type's Mbase object specifically refer to? In Android deep four components (i) application start-up process (later) in this article, we talked about the Activitythread launch activity that invokes the following code to create the context of the activity.
Frameworks/base/core/java/android/app/activitythread.java
private Activity Span class= "Hljs-title" >performlaunchactivity (Activityclientrecord R, Intent customintent) {... if (activity! = null ) {Context AppContext = Createbasecontextforactivity (R, activity); //1 ...} Activity.attach (AppContext, this , Getinstrumentation (), R.token, R.ident, App, R.intent, R.activityinfo, title, R.parent, R.embeddedid, R.lastnonconfigurationinstan Ces, config, r.referrer, r.voiceinteractor, window); ... } return activity;}
Create the context object Appcontext at note 1 and pass in the activity's attach method, associating the activity with the context object Appcontext, what is the specific type of the context object Appcontext, We then look at the Createbasecontextforactivity method, as shown in the code below.
Frameworks/base/core/java/android/app/activitythread.java
privatecreateBaseContextForActivityfinal Activity activity) {... ContextImpl appContext = ContextImpl.createActivityContext( this, r.packageInfo, r.token, displayId, r.overrideConfig); appContext.setOuterContext(activity); Context baseContext = appContext; ... return baseContext;}
It can be concluded here that the specific type of context object Appcontext is Contextimpl. The activity's attach method assigns Contextimpl to the Contextwrapper member variable mbase, so mbase is specifically directed to Contextimpl.
So, let's look at Contextimpl's StartService method, as shown in the code below.
Frameworks/base/core/java/android/app/contextimpl.java.java
Override PublicComponentNameStartService(Intent service) {warnifcallingfromsystemprocess ();returnStartservicecommon (service, muser);}PrivateComponentNameStartservicecommon(Intent service, Userhandle user) {Try{validateserviceintent (service); Service.preparetoleaveprocess ( This);/** * 1 * *ComponentName cn = Activitymanagernative.getdefault (). StartService (Mmainthread.getapplicationthread (), Ser Vice, service.resolvetypeifneeded (Getcontentresolver ()), Getoppackagename (), User.getidentifie R ()); ...returnAny }Catch(RemoteException e) {ThrowE.rethrowfromsystemserver (); } }
The StartService method will return the Startservicecommon method, The StartService method of the proxy object Activitymanagerproxy (AMP) for Activitymanageservice (AMS) is called at note 1 in the Startservicecommon method, The StartService method of AMs will eventually be called. As for why the code in note 1 calls the AMS StartService method, the Android drill down into the four components (a) Application launch process (previous) This article has already said, here no longer repeat.
The Contextimpl to Activitymanageservice call process is shown in the following timing diagram.
2.ActivityThread Start Service
We will then look at the StartService method of AMs.
Frameworks/base/services/core/java/com/android/server/am/activitymanagerservice.java
overridepublic ComponentName startservice (iapplicationthread caller, Intent service, String resolv Edtype, String callingpackage, int userId) throws transactiontoolargeexception {... synchronized (this ) { ... componentname res = mservices.startservicelocked (caller, service, Resolvedtype, Callingpid, Callinguid, Cal Lingpackage, userId); //1 Binder.restorecallingidentity (Origid); return res; }}
Note 1 calls the Startservicelocked method of Mservices, and the mservices type is activeservices,activeservices startservicelocked method code as shown below.
Frameworks/base/services/core/java/com/android/server/am/activeservices.java
ComponentName startservicelocked (iapplicationthread caller, Intent service, String Resolvedtype,intCallingpid,intCallinguid, String Callingpackage,Final intUSERID)throwstransactiontoolargeexception {...returnstartserviceinnerlocked (SMAP, service, R, CALLERFG, addtostarting); } componentname startserviceinnerlocked (Servicemap SMAP, Intent service, Servicerecord R,BooleanCALLERFG,Booleanaddtostarting)throwstransactiontoolargeexception {... String error = bringupservicelocked (R, Service.getflags (), CALLERFG,false,false); ...returnR.name; }
The Startserviceinnerlocked method is returned at the end of the Startservicelocked method, and the Bringupservicelocked method is called in the Startserviceinnerlocked method:
Frameworks/base/services/core/java/com/android/server/am/activeservices.java
PrivateStringbringupservicelocked(Servicerecord R,intIntentflags,BooleanEXECINFG,BooleanWhilerestarting,Booleanpermissionsreviewrequired)throwstransactiontoolargeexception {...FinalString procname = r.processname;//1Processrecord app;if(!isolated) {app = mam.getprocessrecordlocked (procname, R.appinfo.uid,false);//2 if(DEBUG_MU) SLOG.V (TAG_MU,"Bringupservicelocked:appinfo.uid="+ R.appinfo.uid +"app="+ app);if(App! =NULL&& App.thread! =NULL) {//3 Try{App.addpackage (R.appinfo.packagename, R.appinfo.versioncode, mam.mprocessstats); Realstartservicelocked (r, app, EXECINFG);//4 return NULL; }Catch(Transactiontoolargeexception e) {ThrowE }Catch(RemoteException e) {SLOG.W (TAG,"Exception When starting service"+ R.shortname, E); } } }Else{app = R.isolatedproc; }if(App = =NULL&&!permissionsreviewrequired) {//5 if(App=mam.startprocesslocked (procname, R.appinfo,true, Intentflags,"Service", R.name,false, isolated,false)) ==NULL) {//6... }if(Isolated) {r.isolatedproc = app; } } ... }
The value of Servicerecord's processname at note 1 is assigned to ProcName, where Servicerecord is used to describe the android:process attribute of the service. Note 2 The UID of the procname and service is passed into the Getprocessrecordlocked method of AMs to query for the existence of an object app that corresponds to the Processrecord type of service. Processrecord is primarily used to record information about the running application process. Comment 5 determines that the service corresponding app is NULL, indicating that the application process used to run the service does not exist, then invokes the AMS startprocesslocked method at comment 5 to create the corresponding application process. For more information about creating an application process, see the Android Application process startup process (previous) and the Android application process startup process (later) both articles. Comment 3 Determines if the application process used to run the service exists, call the Realstartservicelocked method at comment 4:
Frameworks/base/services/core/java/com/android/server/am/activeservices.java
private final void realstartservicelocked (Servicerecord R, Processrecord app, boolean ExecInF g) throws remoteexception {... try {... app.thread.scheduleCreateService (R, R.serviceinfo, mam.compatibilityinfoforpackagelocked (R.serviceinfo.applicationinfo), app.repprocstate); R.postnotification (); Created = true ; } catch (deadobjectexception e) {...} ...}
The
Schedulecreateservice method of App.thread was called in the Realstartservicelocked method. Where App.thread is the Iapplicationthread type, its implementation is Activitythread's inner class Applicationthread, where Applicationthread inherits Applicationthreadnative , and Applicationthreadnative inherits the binder and implements the Iapplicationthread interface. The Schedulecreateservice method for Applicationthread is shown below.
Frameworks/base/core/java/android/app/activitythread.java
publicfinalvoidscheduleCreateService(IBinder token, int processState) { false); new CreateServiceData(); s.token = token; s.info = info; s.compatInfo = compatInfo; sendMessage(H.CREATE_SERVICE, s); }
The information to be started is encapsulated into a Createservicedata object and passed to the SendMessage method, and the SendMessage method sends a CREATE_SERVICE message to H. H is the inner class of Activitythread and inherits handler. This process is similar to the application startup process (the root activity startup process). We then look at H's Handlemessage method.
Frameworks/base/core/java/android/app/activitythread.java
public void handlemessage (Message msg) {if (debug_messages) slog.v (TAG, " >>> handling: " + codetostring ( Msg.what)); switch (msg.what) {... case CREATE_SERVICE:Trace.traceBegin (Trace.trace_tag_activity_manager, ( + string.valueof (msg.obj))); Handlecreateservice ((createservicedata) msg.obj); Trace.traceend (Trace.trace_tag_activity_manager); break ; ... } ... } ... }
The Handlemessage method calls the Handlecreateservice method based on the message type:
Frameworks/base/core/java/android/app/activitythread.java
Private void Handlecreateservice(Createservicedata data) {Unschedulegcidler (); loadedapk PackageInfo = Getpackageinfonocheck (Data.info.applicationInfo, data.compatinfo);//1Service service =NULL;Try{Java.lang.ClassLoader cl = Packageinfo.getclassloader ();//2Service = (Service) cl.loadclass (data.info.name). newinstance ();//3}Catch(Exception e) { ... } }Try{if(LOCALLOGV) SLOG.V (TAG,"Creating Service"+ Data.info.name); Contextimpl context = Contextimpl.createappcontext ( This, PackageInfo);//4Context.setoutercontext (service); Application app = Packageinfo.makeapplication (false, minstrumentation); Service.attach (Context, This, Data.info.name, Data.token, App, Activitymanagernative.getdefault ());//5Service.oncreate ();//6Mservices.put (Data.token, service);//7... }Catch(Exception e) { ... } }
Note 1 The loadedapk,loadedapk for the application to start the service is a description class for the APK file. Note 2 Gets the class loader by calling the getClassLoader method of loadedapk. The service is then loaded into memory at note 3 based on the service information stored in the Createservicedata object. Note 4 Creates a service context Contextimpl object. Note 5 Initializes the service with the service's attach method. Comment 6 invokes the service's OnCreate method so that the service is started. At note 7, the started service is added to the member variable mservices of Activitythread, where mservices is the Arraymap type.
Finally, a time series diagram of this section is given.
Welcome to my public number, the first time to get blog update reminders, and more into the system of Android-related original technology dry.
Sweep the two-dimensional code below or long press identification QR code, you can pay attention to.
Android deep four components (ii) service start-up process