Android源码分析之SystemServer系统服务创建过程

本文的分析基于Android1.6系统源码,之所以选择较低版本的系统源码,是因为它代码量较少,能够比较容易分析Android系统的核心本质。对于高版本的系统,读者可以进行对比分析,效果会很好。

一、SystemServer进程创建过程简要说明

《Android源码分析之SystemServer系统服务创建过程》 p1.png

如上图所示,执行adb shell ps可以查看当前系统上运行的进程列表。从上图可以得知,system_server进程是由进程号为30的zygote进程fork而来的,而zygote进程是由进程号为1的/init进程fork创建的。zygote进程的主要功能就是进行进程孵化,后续的应用进程都由它创建。system_server进程运行着很多系统服务,当其它的应用进程需要某些系统提供的功能时,应用程序会以代理的方式向这些系统服务发出请求,系统服务处理后将结果返回给应用进程。
system_server进程的名称在DDMS上不叫“system_server”,而是变成了“system_process”,是因为system_server进程在执行ActivityThread.attach方法时将在DDMS上显示的名称改成了“system_process”,详见下面的代码片段。

//在ActivityThread.java文件中
   private final void attach(boolean system) {
        sThreadLocal.set(this);
        mSystemThread = system;
        AndroidHttpClient.setThreadBlocked(true);
        if (!system) {
            android.ddm.DdmHandleAppName.setAppName("<pre-initialized>");
            RuntimeInit.setApplicationObject(mAppThread.asBinder());
            IActivityManager mgr = ActivityManagerNative.getDefault();
            try {
                mgr.attachApplication(mAppThread);
            } catch (RemoteException ex) {
            }
        } else {
            // Don't set application object here -- if the system crashes,
            // we can't display an alert, we just want to die die die.
            android.ddm.DdmHandleAppName.setAppName("system_process");
            try {
                mInstrumentation = new Instrumentation();
                ApplicationContext context = new ApplicationContext();
                context.init(getSystemContext().mPackageInfo, null, this);
                Application app = Instrumentation.newApplication(Application.class, context);
                mAllApplications.add(app);
                mInitialApplication = app;
                app.onCreate();
            } catch (Exception e) {
                throw new RuntimeException(
                        "Unable to instantiate Application():" + e.toString(), e);
            }
        }
    }

二、系统服务的创建过程

《Android源码分析之SystemServer系统服务创建过程》 SystemServer时序图.jpg

system_server进程创建系统服务的过程可以通过上述的时序图进行描述,时序图可以很清晰的描述对象的调用过程,接下来结合代码和时序图一起分析一下系统服务的创建过程。

 //在SystemServer.java文件中
   public static void main(String[] args) {
        // The system server has to run all of the time, so it needs to be
        // as efficient as possible with its memory usage.
        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
        
        System.loadLibrary("android_servers");
        init1(args);
    }

上述的代码片段会在system_server进程的主线程中被执行,首先它会调用 VMRuntime.getRuntime().setTargetHeapUtilization方法来设置堆的使用率,进而对堆内存进行一个比较合理的优化。然后加载libandroid_servers.so并调用native的init1方法。init1方法在com_android_server_SystemServer.cpp文件中,可以看出在Android系统源码中java层跟native层存在一种对应关系,即native方法实现类的文件名一般会以“包名+类名”进行命名,所以可以通过这种对应关系找到native方法的实现代码。

//在com_android_server_SystemServer.cpp文件中
extern "C" int system_init();

static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
{
    system_init();
}

在init1方法中调用了system_init的system_init方法。

//在system_init文件中
extern "C" status_t system_init()
{
    LOGI("Entered system_init()");
    
    sp<ProcessState> proc(ProcessState::self());
    
    sp<IServiceManager> sm = defaultServiceManager();
    LOGI("ServiceManager: %p\n", sm.get());
    
    sp<GrimReaper> grim = new GrimReaper();
    sm->asBinder()->linkToDeath(grim, grim.get(), 0);
    
    char propBuf[PROPERTY_VALUE_MAX];
    property_get("system_init.startsurfaceflinger", propBuf, "1");
    if (strcmp(propBuf, "1") == 0) {
        // Start the SurfaceFlinger
        SurfaceFlinger::instantiate();
    }

    // On the simulator, audioflinger et al don't get started the
    // same way as on the device, and we need to start them here
    if (!proc->supportsProcesses()) {

        // Start the AudioFlinger
        AudioFlinger::instantiate();

        // Start the media playback service
        MediaPlayerService::instantiate();

        // Start the camera service
        CameraService::instantiate();
    }

    // And now start the Android runtime.  We have to do this bit
    // of nastiness because the Android runtime initialization requires
    // some of the core system services to already be started.
    // All other servers should just start the Android runtime at
    // the beginning of their processes's main(), before calling
    // the init function.
    LOGI("System server: starting Android runtime.\n");
    
    AndroidRuntime* runtime = AndroidRuntime::getRuntime();

    LOGI("System server: starting Android services.\n");
    runtime->callStatic("com/android/server/SystemServer", "init2");
        
    // If running in our own process, just go into the thread
    // pool.  Otherwise, call the initialization finished
    // func to let this process continue its initilization.
    if (proc->supportsProcesses()) {
        LOGI("System server: entering thread pool.\n");
        ProcessState::self()->startThreadPool();
        IPCThreadState::self()->joinThreadPool();
        LOGI("System server: exiting thread pool.\n");
    }
    return NO_ERROR;
}

在system_init方法中,会通过调用SurfaceFlinger、AudioFlinger、MediaPlayerService、CameraService的instantiate方法来创建native层系统服务,native层的系统服务创建完毕之后,它又调用java层的init2方法来进行java层的系统服务创建工作。

//在SystemServer.java文件中
    public static final void init2() {
        Log.i(TAG, "Entered the Android system server!");
        Thread thr = new ServerThread();
        thr.setName("android.server.ServerThread");
        thr.start();
    }

在init2方法中开启了一个名叫android.server.ServerThread的线程来创建系统服务。在ServerThread的run方法中,创建了java层的很多的核心服务,比如ActivityManagerService、WindowManagerService等等,并且该线程使用了Looper机制,会在后台一直运行,通过DDMD->Threads视图可以看到该线程一直在后台运行着。因为核心服务的创建过程比较复杂,不适合在这边进行描述,后续会对部分核心服务逐一展开进行分析。

《Android源码分析之SystemServer系统服务创建过程》 p2.png

三、系统服务一览表

服务名称作用描述
SurfaceFlinger将逻辑窗口的数据合成到物理窗口进行显示(Native)
AudioFlinger音频系统服务(Native)
MediaPlayerService媒体播放服务(Native)
CameraService相机服务(Native)
ActivityManagerServiceAndroid系统中最核心的一个服务,主要管理四大组件的生命周期。
EntropyService熵服务,周期性的加载和保存随机信息
PowerManagerService电源管理服务
TelephonyRegistry电话注册、管理服务
BatteryService监控电池状态的服务
HardwareService主要负责震动、闪光灯等服务
AlarmManagerService闹钟服务
SensorService传感器服务
WindowManagerService窗口管理服务,主要负责事件分发等服务
BluetoothDeviceService蓝牙服务
StatusBarService状态栏服务
AppWidgetService桌面上的Wiget的管理服务
ClipboardService剪贴板服务
InputMethodManagerService输入法管理服务
NetStatService网络统计服务
AccessibilityManagerService跟辅助功能相关的服务
NotificationManagerService通知栏服务
MountService磁盘挂载服务
DeviceStorageMonitorService监控磁盘空间的服务
LocationManagerService地址位置信息服务
SearchManagerService搜索服务
WallpaperService壁纸服务
AudioService音频服务
BackupManagerService备份管理服务

四、总结

《Android源码分析之SystemServer系统服务创建过程》 p3.png

上图为Android系统的框架图,本文所讨论的系统服务在Application Framework即应用程序框架层,它抽象封装了很多组件、实现了很多系统服务。对于Applications即应用程序而言,就是将这些组件按照业务功能进行一个组合,按需调用系统服务。所以要学好android,就要将这些核心的系统服务和组件进行深入分析,只有知其所以然,才能够将应用性能提升到极致。才能实现组件化、热修复等黑科技。

    原文作者:安卓程序员小黄
    原文地址: https://www.jianshu.com/p/2aad9a8743b3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞