android启动过程分析--启动systemServer

转载:http://blog.csdn.net/new_abc/article/details/7439200


System Server是Android系统的核心,他在Dalvik虚拟机启动后立即开始初始化和运行。其它的系统服务在System Server进程的环境中运行.

systemServer是通过zygote启动的时候fork启动的,我们先看下它的启动大概流程:

创建systemServer进程

在zygote启动过程中,通过调用startSystemServer启动systemServer:

 private static boolean startSystemServer()

            throws MethodAndArgsCaller,RuntimeException {

        /* Hardcoded command line to start thesystem server */

        String args[] = {

            "--setuid=1000",

            "--setgid=1000",

           "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,3001,3002,3003",

           "--capabilities=130104352,130104352",

            "--runtime-init",

           "--nice-name=system_server",

            "com.android.server.SystemServer",

        };

        ZygoteConnection.Arguments parsedArgs =null;

 

        int pid;

 

        try {

            parsedArgs = newZygoteConnection.Arguments(args);

 

            /*

             * Enable debugging of the systemprocess if *either* the command line flags

             * indicate it should be debuggableor the ro.debuggable system property

             * is set to "1"

             */

            int debugFlags = parsedArgs.debugFlags;

            if("1".equals(SystemProperties.get("ro.debuggable")))

                debugFlags |=Zygote.DEBUG_ENABLE_DEBUGGER;

 

            /* Request to fork the systemserver process */

            pid = Zygote.forkSystemServer(

                    parsedArgs.uid, parsedArgs.gid,

                    parsedArgs.gids,debugFlags, null,

                   parsedArgs.permittedCapabilities,

                   parsedArgs.effectiveCapabilities);

        } catch (IllegalArgumentException ex) {

           throw newRuntimeException(ex);

        }

 

        /* For child process */

        if (pid == 0) {

           handleSystemServerProcess(parsedArgs);

        }

 

        return true;

    }


首先通过Zygote.forkSystemServer fork出一个子进程来,并传入了一些参数来设置新进程的一些信息,如uid、gid等,函数返回后,如果是子进程pid=0,进入handleSystemServerProcess:

    private static voidhandleSystemServerProcess(

            ZygoteConnection.ArgumentsparsedArgs)

            throwsZygoteInit.MethodAndArgsCaller {

 

        closeServerSocket();

 

        /*

         * Pass the remaining arguments toSystemServer.

         * "--nice-name=system_servercom.android.server.SystemServer"

         */

       RuntimeInit.zygoteInit(parsedArgs.remainingArgs);

        /* should never reach here */

    }

这里先关闭socket,然后调用zygoteInit

public static final voidzygoteInit(String[] argv)

            throwsZygoteInit.MethodAndArgsCaller {

        commonInit();

        zygoteInitNative();

         ...

        invokeStaticMain(startClass,startArgs);

}

调用commonInit初始化时区,zygoteInitNative是jni函数,最终会调用app_main.cpp中的onZygoteInit

 virtual void onZygoteInit()

    {

        sp<ProcessState> proc =ProcessState::self();

        if (proc->supportsProcesses()) {

            LOGV("App process: startingthread pool.\n");

            proc->startThreadPool();

        }      

    }

这里启动线程池处理Binder事件 。

然后调用invokeStaticMain启动SystemServer的main函数中

 

    public static void main(String[] args) {

        if (System.currentTimeMillis() <EARLIEST_SUPPORTED_TIME) {

            // If a device's clock is before1970 (before 0), a lot of

            // APIs crash dealing with negativenumbers, notably

            // java.io.File#setLastModified, soinstead we fake it and

            // hope that time from cell towersor NTP fixes it

            // shortly.

            Slog.w(TAG, "System clock isbefore 1970; setting to 1970.");

           SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);

        }

 

        if(SamplingProfilerIntegration.isEnabled()) {

            SamplingProfilerIntegration.start();

            timer = new Timer();

            timer.schedule(new TimerTask() {

                @Override

                public void run() {

                   SamplingProfilerIntegration.writeSnapshot("system_server");

                }

            }, SNAPSHOT_INTERVAL,SNAPSHOT_INTERVAL);

        }

 

        // The system server has to run all ofthe time, so it needs to be

        // as efficient as possible with itsmemory usage.

       VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

       

       System.loadLibrary("android_servers");

        init1(args);

    }

首先检查系统时间设置和SamplingProfiler。然后加载一个叫android_servers的本地库,然后调用init1启动本地服务,因为后面要启动的java服务依赖这些服务。init1()也是个jni函数,最终调用system_init.cpp中的system_init()函数

extern "C" status_tsystem_init()

{

    LOGI("Entered system_init()");

   

    sp<ProcessState>proc(ProcessState::self());

   

    sp<IServiceManager> sm =defaultServiceManager();

    LOGI("ServiceManager: %p\n", sm.get());

   

    sp<GrimReaper> grim = newGrimReaper();

    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();

    }

 

    // Start the sensor service

    SensorService::instantiate();

 

    // On the simulator, audioflinger et aldon't get started the

    // same way as on the device, and we needto start them here

    ......

    // the init function.

    LOGI("System server: starting Androidruntime.\n");

   

    AndroidRuntime* runtime =AndroidRuntime::getRuntime();

 

    LOGI("System server: starting Androidservices.\n");

   runtime->callStatic("com/android/server/SystemServer","init2");

    if (proc->supportsProcesses()) {

        LOGI("System server: enteringthread pool.\n");

       ProcessState::self()->startThreadPool();

        IPCThreadState::self()->joinThreadPool();

        LOGI("System server: exitingthread pool.\n");

    }

    return NO_ERROR;

}


在这里根据设置是否启动SurfaceFlinger,启动SensorService,然后调用java函数init2启动java服务,启动线程池,由于前面已经调用过startThreadPool,故此次调用不做任何事情,最后把主要线程加入线程池。

    public static final void init2() {

        Slog.i(TAG, "Entered the Androidsystem server!");

        Thread thr = new ServerThread();

       thr.setName("android.server.ServerThread");

        thr.start();

    }


在这里,new一个ServerThread,并启动这个线程。进入它的run方法

 public void run() {

      ...

       try {

            Slog.i(TAG, "EntropyService");

           ServiceManager.addService("entropy", new EntropyService());

      }

      ...

       Slog.i(TAG, "ActivityManager");

       context = ActivityManagerService.main(factoryTest);

      Slog.i(TAG, "Package Manager");

       pm = PackageManagerService.main(context,

                    factoryTest !=SystemServer.FACTORY_TEST_OFF);

 

     ActivityManagerService.setSystemProcess();

    ...

    Slog.i(TAG, "Window Manager");

     wm = WindowManagerService.main(context,power,

                    factoryTest !=SystemServer.FACTORY_TEST_LOW_LEVEL);

     ((ActivityManagerService)ActivityManagerNative.getDefault())

                .systemReady(new Runnable() {

      ...

      }

      ...

      Looper.loop();

      Slog.d(TAG, "System ServerThread isexiting!");

}

在这里实现了Java Service的注册及初始化操作,PackageManagerService、ActivityManagerService等主要服务都是在这里启动的,ActivityManagerService.systemReady()函数来启动Home应用程序。

最后调用loop进入SystemServer事件处理循环。

到这里,SystemServer就已经启动起来了,各种服务也已经加载 了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值