Android System Services

Source: Internet
Author: User
Tags local time throwable ssl certificate

The Android system service is broadly divided into three broad categories: The local daemon, the native system service, and the Java system service. As shown in the following:

Local daemon Process

The init process initiates the local daemon based on the definition in the Init.rc file. These processes will be resident in the system, some will only be started once, and others will be started by Init if they are exited. The specific start-up method is defined in init.rc.
The following outlines several daemons and their functions.

Daemon Process function
Vold Manage storage devices, automatically install storage devices, format device partitions
Netd Manage various network connections such as Bluetooth, WiFi, USB, etc.
Installd Responsible for installing and uninstalling software packages and verifying package integrity
Rild Receive a modem control request from the phone application or other client program and pass it to
adbd Provides an environment where android can be debugged
ServiceManager Binder Communications Big Butler
Surfaceflinger Graphical display of the UI for the Android system
MediaServer Responsible for playing audio, video, camera photo recording
Native System Services

Written by the C + + language and run in the local daemon. For example, the MediaServer daemon contains Audioflinger, Mediaplayerservice, Cameraservice, Audiopolicyservice, and Soundtriggerhwservice services. In
In the main function of the mediaserver process, initialize the instances of these services with the following code:

int main(int argc __unused, char** argv){    ...    sp<ProcessState> proc(ProcessState::self());    sp<IServiceManager> sm = defaultServiceManager();    ALOGI("ServiceManager: %p", sm.get());    AudioFlinger::instantiate();    MediaPlayerService::instantiate();    CameraService::instantiate();    AudioPolicyService::instantiate();    SoundTriggerHwService::instantiate();    ...    ProcessState::self()->startThreadPool();    IPCThreadState::self()->joinThreadPool();}

The native system service is registered to ServiceManager when the owning process is initialized. In this way, other applications or services can invoke the native system service through the binder mechanism.
Of course, we can also develop a native system service to implement its binder interface, so that the service can be invoked by other applications or services on the native layer.
If the native system service we develop wants to be available to Java-tier applications, it is necessary to implement a Java interface and then invoke native system services through JNI.

Java System Services

Written by the Java language, most of them run in the system_server process. Each system service runs in the form of a thread, waits for requests made by the application, processes the request process, and then returns the results back to the application.
This part of the system services can be divided into two kinds: Java Core system Services and Java hardware system services.
The Java Core System service is the basis of the normal operation of Android system, including the familiar AMS, WMS, PMS and so on.
Java Hardware Services provide hardware control services for applications such as telephony, WiFi services, Powermanagerservice, and so on.

The following is a list of system services running in System_server, sorted alphabetically.

Accessibilitymanagerservice intercepts the user input and gives the user some additional feedback based on the input, and serves as an ancillary effect.
Accountmanagerservice management of all accounts in the device, including account number, password, authorization management function
Activitymanagerservice manages all components of the service, the core service of the Android system alarmmanagerservice the service of alarm clock management
Appwidgetservice manages the work of app widgets, including loading, deleting, layout, etc.
Assetatlasservice Some system picture resources into a texture map to the GPU to achieve hardware-accelerated performance of the service
Audioservice Services for managing audio
Backupmanagerservice Services for managing backup and application Data
Batteryservice Management of battery services
Bluetoothmanagerservice Management System Bluetooth service
Certblacklister Update system SSL certificate public key and serial number blacklist service
Clipboardservice Management system Clipboard Services
Commontimemanagementservice managing public-time configuration services
Connectivityservice managing network-connected services
Contentservice Management System Data Update Notification Service, which is closely related to ContentProvider
Countrydetectorservice detection of services in the country of the current system
Devicepolicymanagerservice Management System Device Configuration services
Devicestoragemonitorservice A service that manages the storage space of a system, which emits a warning broadcast when the storage space is less than a threshold value
Diskstateservice Management system storage space statistics Services
Displaymanagerservice Management of display device services
Dreammanagerservice Manage screen-protected services
Dropboxmanagerservice services for generating and managing log files in a system run
Entropymixer loading and saving of random information services
Idlemaintenanceservice Management system performs maintenance tasks during idle service
Inputmanagerservice Services for managing touch input
Service of Inputmethodmanagerservice Management system input Method
Lightsservice Management of light sensor services
Locationmanagerservice management of positioning and location services
Locksettingsservice Management System lock screen setting services
Mountservice Management System storage device mount and uninstall services
Service of Networkmanagementservice Management System network
Networkpolicymanagerservice Services for managing network connection policies
Networkstatsservice Services to manage network connection status
Networktimeupdateservice service to update local time based on network time
Notificationmanagerservice Service for Management system notifications
Packagemanagerservice services for managing app packages
Powermanagerservice Management system power supply services
Printmanagerservice Managing printed Services
Recognitionmanagerservice managing identity-aware services
Samplingprofilerservice Service for recording and analyzing system startup performance
Service of Schedulingpolicyservice management system scheduling policy
Service of Searchmanagerservcie Management system search function
Serialservie Management System serial Device service
Statusbarmanagerservice Services for the management system status bar
Telephonyregistry services for monitoring and managing call events and Status
Textservicesmanagerservice Text spelling checker services
Uimodemanagerservice services for setting up and managing system UI patterns
Usbservice managing USB-connected Services
Usermanagerservice Management System user identity information Services
Service of Vibratorservice Management system Vibrator
Wallpapermanagerservice Management system desktop background wallpaper Service
Wifip2pservice services for managing WiFi point-to-point connections
Wifiservice Management System WiFi Device Services
Windowmanagerservice Management window Services, core services of the Android system

implementation of Java system Services

From android5.1.1, Java service typically inherits a virtual class Systemservice, where two interfaces OnStart and onbootphase are defined.

    • OnStart (): The function is invoked when the Java service is started.
    • Onbootphase (): The function is recalled at each stage of the system startup.

In this way, starting the service is simple:

mSystemServiceManager.startService(xxxxxxService.class);

Let's continue to look at the implementation of StartService:

public class Systemservicemanager {//Save all Systemservice private FINA    L arraylist<systemservice> mservices = new arraylist<systemservice> ();        Public Systemservice StartService (String className) {final class<systemservice> serviceclass; try  {//calls the JVM to load classname the specified class, executes the class's static code snippet ServiceClass = (class<systemservice>) class.forname (classn         AME);        } catch (ClassNotFoundException ex) {        }  ...  Mservices.add (service);            Add the service try  {service.onstart ();//callback The service's OnStart method            } catch (RuntimeException ex) {    }  ...  }}

Here's a look at the Onbootphase callback method.
In some stages of system startup, the following code is called to proactively callback Systemservice's Onbootphase method.

Msystemservicemanager.startbootphase (SYSTEMSERVICE.PHASE_XXXXXX); Public  class systemservicemanager {     Public void Startbootphase(Final intPhase) {The //stage value will become larger as the system starts, so the next stage value must be greater than the current stage        if(Phase <= Mcurrentphase) {Throw NewIllegalArgumentException ("Next phase must be larger than previous"); } mcurrentphase = phase;//Save current stage        //Traverse all Systemservice, and callback its Onbootphase method.         Final intServicelen = Mservices.size (); for(inti =0; i < Servicelen; i++) {FinalSystemservice Service = Mservices.get (i);Try{service.onbootphase (mcurrentphase);//Pass the stage value in}Catch(Exception ex)        {                ...            } }    }   }

The phase_xxxxxx indicates the various start-up phases, defined as follows:

 Public Abstract  class systemservice {        Public Static Final intPhase_wait_for_default_display = -; Public Static Final intPhase_lock_settings_ready =480; Public Static Final intPhase_system_services_ready = -; Public Static Final intPhase_activity_manager_ready =550; Public Static Final intPhase_third_party_apps_can_start = -; Public Static Final intphase_boot_completed = +;}

So, in onbootphase (int phase), we can do different actions according to the starting stage indicated in phase! This is important when designing a new system service yourself. Because some operations require the support of the system environment, with this callback function and the phase parameter, we can do the appropriate operation at the appropriate stage.

In addition, Java System services generally implement a method: Systemready (). This method is called in Systemserver.java–>startotherservices ():

final XXXService xxxService;mActivityManagerService.systemReady(new Runnable() {    @Override    public void run() {        try {            if (xxxService != null) xxxService.systemReady();        } catch (Throwable e) {            reportWtf("making XXX Service ready", e);        }    ...    }}    

In the [Android5.1]activitymanagerservice startup process Analysis, we know that the AMS Systemready method will callback this runnable, and the code above will execute.

Note: The Java system Services OnStart, Onbootphase, Systemready, and so on, are all running in the System_server main thread. It is recommended that you create a new thread to handle complex, time-consuming operations.

Java System Services Binder Communication

With the implementation of the Java System service, the question is, how do other services or applications invoke the functionality of the Java system service? Communication via binder is of course.
Let's talk about the binder service implementation of Java system services. Assume that the service name is Exampleservice.
First, you need to create and implement three files:

Frameworks/base/core/java/android/app/iexample.aidl
Frameworks/base/core/java/android/app/example.java
Frameworks/base/services/core/java/android/server/exampleservice.java

The FRAMEWORKS/BASE/CORE/JAVA/ANDROID/APP/IEXAMPLE.AIDL code is as follows:

interface IExample {    booleanstr);}

The Frameworks/base/core/java/android/app/example.java code is as follows:

class Example {    privatefinal IExample mService;    Example(Context context, IExample service) {        mService = service;    }    publicbooleanstr) {        try {            return mService.helloWorld(str);        catch(RemoteException e) {            returnnull;        }    }}

The Frameworks/base/services/core/java/android/server/exampleservice.java code is as follows:

Class Exampleservice extends Systemservice {private Context mcontext;        Public Exampleservice (Context context) {super (context);    Mcontext = context;    } @Override public void OnStart () {Publishbinderservice (Context.example_service, New Binderservice ()); } @Override public void onbootphase (int phase) {if(phase = = Phase_system_services_ready) {...}if(phase = = Phase_activity_manager_ready) {...}if(phase = = phase_boot_completed) {...}...} public void Systemready () {...} class Binderservice extend Iexample.stub {@Override boolean helloWorld (String str) {...}    }   }

Next, modify the code for the following file:

Frameworks/base/services/java/com/android/server/systemserver.java
Frameworks/base/core/java/android/content/context.java
Frameworks/base/core/java/android/app/systemserviceregistry.java

    • Frameworks/base/services/java/com/android/server/systemserver.java modified as follows:
import com.android.server.ExampleService;public final class SystemServer {    ExampleService mExampleService = null;    ...    private void startOtherServices() {        ...        mExampleService = mSystemServiceManager.startService(ExampleService.class);        ...        try {            if (mExampleService != null) mExampleService.systemReady();        } catch (Throwable e) {            reportWtf("making Example Service ready", e);        }        ...    }
    • Frameworks/base/core/java/android/content/context.java modified as follows:
public abstract class Context {    ...    "example";    ...}
    • Frameworks/base/core/java/android/app/systemserviceregistry.java modified as follows:
final class SystemServiceRegistry {    ...    registerService(Context.EXAMPLE_SERVICE, Example.class,            new CachedServiceFetcher<Example>() {        @Override        public Example createService(ContextImpl ctx) {            IBinder b = ServiceManager.getService(Context.EXAMPLE_SERVICE);            IExample service = IExample.Stub.asInterface(b);            if (service == null) {                "Failed to get Example Service.");            }            return new Example(ctx.getOuterContext(),service);            }});    ...}

Finally, other applications or services call Exampleservice's HelloWorld method through binder, with the following code:

import android.app.Example;class Client {    static Example mService;    mService = (Example) context.getSystemService(Context.EXAMPLE_SERVICE);    mService.helloWorld(str);}

Android System Services

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.