Android Context Getsystemservice Analysis

Source: Internet
Author: User

We know that the context number of an application is the number of activity +service number +1

When we want to get to the system service, we can call the Getsystemservice method of the context, such as Get to Activitymanager:

ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

So how does Getsystemservice work?

Activity is a context, and when he calls Getsystemservice, it calls into the context wrapper class Contextwrapper's Getsystemservice method, as follows:

@OverridepublicgetSystemService(String name) {    return mBase.getSystemService(name);}

Mbase is the implementation class Contextimpl of the context, it is obvious that Contextwrapper will entrust Contextimpl to implement concrete logic.

We follow up the Getsystemservice method in Contextimpl, as follows:

@OverridepublicgetSystemService(String name) {    return SystemServiceRegistry.getSystemService(this, name);}

The internal is called the Systemserviceregistry Getsystemservice method, then the process of acquiring the system service is transferred to the systemserviceregistry.

We can see the Getsystemservice method of Systemserviceregistry, as follows:

/** * Gets a system service from a given context. */publicstaticgetSystemService(ContextImpl ctx, String name) {    ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);    returnnullnull;}

It seems that there is not much information to be seen. What is System_service_fetchers.get (name)?

The system_service_fetchers is a storage servicefetcher HashMap

privatestaticfinal HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =        new HashMap<String, ServiceFetcher<?>>();

We don't care what the System_service_fetchers.get (name) return value is,

First find out when Servicefetcher was stored in the system_service_fetchers.

There is a static code block in Systemserviceregistry that looks like this:

Static{//Code omissionRegisterservice (Context.activity_service, Activitymanager.class,NewCachedservicefetcher<activitymanager> () {@Override         PublicActivitymanagerCreateService(Contextimpl CTX) {return NewActivitymanager (Ctx.getoutercontext (), Ctx.mMainThread.getHandler ());    }}); Registerservice (Context.alarm_service, Alarmmanager.class,NewCachedservicefetcher<alarmmanager> () {@Override         PublicAlarmmanagerCreateService(Contextimpl CTX)            {IBinder b = servicemanager.getservice (Context.alarm_service); Ialarmmanager service = IAlarmManager.Stub.asInterface (b);return NewAlarmmanager (service, CTX); }});//Code omission}

Static code blocks are executed only when the virtual machine loads the class for the first time.

The static code block calls the Registerservice method to register the system service, and the Registerservice method internally saves the key and value in System_service_fetchers, which is found as follows:

/** * Statically registers a system service with the context. * This method must be called during static initialization only. */privatestaticvoidregisterService(String serviceName, Class<T> serviceClass,        ServiceFetcher<T> serviceFetcher) {    SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);    SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);}

You can see that the servicefetcher is stored, and servicename is the string we pass in, such as
Context.activity_service

We analyze Activitymanager can, in the register Activitymanager when the Registerservice method is Cachedservicefetcher, Then we follow Cachedservicefetcher to see.

/** * Override This class if the system service constructor needs a * Contextimpl and should be cached and retained By that context. */Static AbstractClass Cachedservicefetcher<t> implements Servicefetcher<t> {Private Final intMcacheindex; Public Cachedservicefetcher() {mcacheindex = sservicecachesize++; }@Override    @SuppressWarnings("Unchecked") Public FinalTGetService(Contextimpl CTX) {Finalobject[] cache = Ctx.mservicecache;synchronized(cache) {//Fetch or create the service.Object service = Cache[mcacheindex];if(Service = =NULL) {service = CreateService (CTX);            Cache[mcacheindex] = Service; }return(T) Service; }    } Public AbstractTCreateService(Contextimpl ctx);}

Cachedservicefetcher implements the Servicefetcher interface, this getservice method is triggered in the first Getsystemservice method, as follows

returnnullnull;

Well, it turned out to be servicefetcher to get the system service.

Here we analyze cachedservicefetcher to know that when the service is first fetched, CreateService is called to create the instance and then the service object is added to the cache. The next time you fetch it, you get it directly from the cache. In fact, this is a singleton pattern implemented using containers.

Finally, let's summarize: when we call the Getsystemservice method of the context to get the service, we go to the Getsystemservice method of the Systemserviceregistry class, In this getsystemservice method, according to key, which is the string we passed in, such as Context.activity_service. The GetService method of the Servicefetcher instance gets to the system service object, based on the incoming key from the System_service_fetchers HashMap to the Servicefetcher instance. If this is the first time a system service is obtained, the Servicefetcher CreateService method is called to create the system service instance and add it to the cache list, which is then fetched from the cache.

And what about static code blocks? In fact, the following code is executed for each system service

SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);

The static code blocks in the systemserviceregistry will only be executed once, telling the system that I have these services, adding some keys and value into the HashMap. is some initialization work. And there's no real way to create a system service object because CreateService hasn't been called yet.

Well, the above is the context of the Getsystemservice method of working process analysis. I learned from this that there is a singleton pattern that uses containers.

Reprint Please specify source: http://blog.csdn.net/xyh269

Android Context Getsystemservice Analysis

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.