android 启动的流程

android 启动的流程 

Linux  
BootLoader 作用->  加载驱动 启动硬件 加载linux内核 
系统的第一个进程 init 进程 对应的启动的代码 init.c
system/core/init/init.c
main方法
创建重要的系统目录 并且加载进来
   
   mkdir("/dev", 0755);
   mkdir("/proc", 0755);
   mkdir("/sys", 0755);
   mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
   mkdir("/dev/pts", 0755);
   mkdir("/dev/socket", 0755);
   mount("devpts", "/dev/pts", "devpts", 0, NULL);
   mount("proc", "/proc", "proc", 0, NULL);
   mount("sysfs", "/sys", "sysfs", 0, NULL);

   init_parse_config_file("/init.rc"); //解析init.rc配置文件 这个配置文件中都是linux命令 解析这些命令并且执行


system/core/rootdir/init.rc
跟启动相关 比较重要的部分
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
    class main
    socket zygote stream 660 root system
    onrestart write /sys/android_power/request_state wake
    onrestart write /sys/power/state on
    onrestart restart media
    onrestart restart netd

以服务的形式启动 zygote进程   
zygote进程 是android中十分重要的进程 孵化器进程(受精卵) 所有的android应用进程以及重要的系统进程都是有这个zygote进程 通过fork
以复制自身的形式创建的
1.service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
2.service zygote 以服务的形式启动zygote 
3./system/bin/app_process 启动的时候对应的文件路径   
 --zygote --start-system-server启动是传入的参数


App_main.cpp
main方法
...... 
const char* className = NULL;
    while (i < argc) {
        const char* arg = argv[i++];
        if (!parentDir) {
            parentDir = arg;
        } else if (strcmp(arg, "--zygote") == 0) {//遍历传入的字符串数组  --zygote --start-system-server
            zygote = true;
            niceName = "zygote"; //这里会被执行
      } else if (strcmp(arg, "--start-system-server") == 0) {
          startSystemServer = true;   //这里会被执行
      } else if (strcmp(arg, "--application") == 0) {
          application = true;
      } else if (strncmp(arg, "--nice-name=", 12) == 0) {
          niceName = arg + 12;
      } else {
          className = arg;
          break;
      }
  }

  if (niceName && *niceName) {
      setArgv0(argv0, niceName);
      set_process_name(niceName); //给当前进程起名字为zygote
  }

  runtime.mParentDir = parentDir;

  if (zygote) {
      runtime.start("com.android.internal.os.ZygoteInit",
              startSystemServer ? "start-system-server" : "");  //调用runtime.start方法(ZygoteInit start-system-server)
  } 

....

runtime.start("com.android.internal.os.ZygoteInit", "start-system-server" );
runtime.start  ①给当前的进程创建了一个java虚拟机 ②通过jni的调用 启动了ZygoteInit.java的main方法 启动了第一个java程序

void AndroidRuntime::start(const char* className, const char* options)
{
    ALOGD("\n>>>>>> AndroidRuntime START %s <<<<<<\n",
            className != NULL ? className : "(unknown)");

    blockSigpipe();

    /*
     * 'startSystemServer == true' means runtime is obsolete and not run from
     * init.rc anymore, so we print out the boot start event here.
     */
    if (strcmp(options, "start-system-server") == 0) {
        /* track our progress through the boot sequence */
        const int LOG_BOOT_PROGRESS_START = 3000;
        LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,
                       ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
    }

    const char* rootDir = getenv("ANDROID_ROOT");
    if (rootDir == NULL) {
        rootDir = "/system";
        if (!hasDir("/system")) {
            LOG_FATAL("No root directory specified, and /android does not exist.");
            return;
        }
        setenv("ANDROID_ROOT", rootDir, 1);
    }

    //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
    //ALOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);

    /* start the virtual machine */
    JNIEnv* env;             //启动java虚拟机
    if (startVm(&mJavaVM, &env) != 0) {
        return;
    }
    onVmCreated(env);

    /*
     * Register android functions.
     */
    if (startReg(env) < 0) {
        ALOGE("Unable to register all android natives\n");
        return;
    }

    /*
     * We want to call main() with a String array with arguments in it.
     * At present we have two arguments, the class name and an option string.
     * Create an array to hold them.
     */
    jclass stringClass;
    jobjectArray strArray;
    jstring classNameStr;
    jstring optionsStr;

    stringClass = env->FindClass("java/lang/String");   通过jni调用 创建了一个java的String[] = {"com.android.internal.os.ZygoteInit", "start-system-server"}
    assert(stringClass != NULL);
    strArray = env->NewObjectArray(2, stringClass, NULL);
    assert(strArray != NULL);
    classNameStr = env->NewStringUTF(className);
    assert(classNameStr != NULL);
    env->SetObjectArrayElement(strArray, 0, classNameStr);
    optionsStr = env->NewStringUTF(options);
 env->SetObjectArrayElement(strArray, 1, optionsStr);

    /*
     * Start VM.  This thread becomes the main thread of the VM, and will
     * not return until the VM exits.
     */
    char* slashClassName = toSlashClassName(className); //通过Jni调用 找到zygoteInit.java的字节码 找到main方法 执行
    jclass startClass = env->FindClass(slashClassName);  
    if (startClass == NULL) {
        ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
        /* keep going */
    } else {
        jmethodID startMeth = env->GetStaticMethodID(startClass, "main", //执行main方法的时候 把刚创建的String[]作为参数穿进去
            "([Ljava/lang/String;)V");
        if (startMeth == NULL) {
            ALOGE("JavaVM unable to find main() in '%s'\n", className);
            /* keep going */
        } else {
            env->CallStaticVoidMethod(startClass, startMeth, strArray);

#if 0
            if (env->ExceptionCheck())
                threadExitUncaughtException(env);
#endif
        }
    }
    free(slashClassName);

    ALOGD("Shutting down VM\n");
    if (mJavaVM->DetachCurrentThread() != JNI_OK)
        ALOGW("Warning: unable to detach main thread\n");
    if (mJavaVM->DestroyJavaVM() != 0)
        ALOGW("Warning: VM did not shut down cleanly\n");
}

到这儿 从native世界 来到了java的程序中


zygoteInit main方法
public static void main(String argv[]) {
        try {
           // Start profiling the zygote initialization.
           SamplingProfilerIntegration.start();

           registerZygoteSocket();  //创建一个socket服务端
           EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
               SystemClock.uptimeMillis());
           preload();                  //预加载资源 包括 两千多个字节码对象  用到的系统图片 颜色资源
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                SystemClock.uptimeMillis());

            // Finish profiling the zygote initialization.
            SamplingProfilerIntegration.writeZygoteSnapshot();

            // Do an initial gc to clean up after startup
            gc();

            // If requested, start system server directly from Zygote
            if (argv.length != 2) {
                throw new RuntimeException(argv[0] + USAGE_STRING);
            }

            if (argv[1].equals("start-system-server")) {
                startSystemServer();                                //开启SystemServer 系统服务
            } else if (!argv[1].equals("")) {
                throw new RuntimeException(argv[0] + USAGE_STRING);
            }

            Log.i(TAG, "Accepting command socket connections");

            if (ZYGOTE_FORK_MODE) {
                runForkMode();
            } else {
                runSelectLoopMode();                                     //开启死循环 等待socket客户端访问
            }

            closeServerSocket();
        } catch (MethodAndArgsCaller caller) {
            caller.run();
        } catch (RuntimeException ex) {
            Log.e(TAG, "Zygote died with exception", ex);
            closeServerSocket();
            throw ex;
        }
    }


zygote启动到这儿就结束了

zygote在启动的过程中 做了如下几件事儿
① zygote进程创建了一个jvm
② zygote创建了一个socket服务端 等待ams给它发消息 分叉新的进程
③ 预加载了资源包括 字节码 图片 颜色
④ 跑起死循环 等待客户端连接
⑤ 创建了SystemServer进程


SystemServer启动的过程
 /**
     * Prepare the arguments and fork for the system server process.
     */
    private static boolean startSystemServer()
            throws MethodAndArgsCaller, RuntimeException {
        /* Hardcoded command line to start the system server */
        String args[] = {
           "--setuid=1000",
           "--setgid=1000",
            "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003,3006,3007",
            "--capabilities=130104352,130104352",
            "--runtime-init",
            "--nice-name=system_server",
            "com.android.server.SystemServer",
        };
        ZygoteConnection.Arguments parsedArgs = null;

        int pid;

        try {
            parsedArgs = new ZygoteConnection.Arguments(args);  //zygote进程 分叉出systemserver进程
            ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
            ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

            /* Request to fork the system server process */
            pid = Zygote.forkSystemServer(
                    parsedArgs.uid, parsedArgs.gid,
                    parsedArgs.gids,
                    parsedArgs.debugFlags,
                    null,
                    parsedArgs.permittedCapabilities,
                    parsedArgs.effectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }

        /* For child process */
        if (pid == 0) {
            handleSystemServerProcess(parsedArgs); //pid为0说明当前的代码执行在子进程中 这个进程就是system_server进程
        }

        return true;
    }


hanldeSystemServerProess->RuntimeInit.zygoteInit->applicationInit->invokestaticMain()->调用了SystemServer.java的main方法
systemServer的main方法 通过jni调用到 systemserver.cpp的init1方法

init1方法 调用了system_init() 在这个方法中 把 显示的驱动和传感器的驱动启动起来
只有这些驱动加载进来了 在java层才能启动相应的服务
通过jni system_init() 方法又调用到systemServer.java的 init2方法

public static final void init2() {
        Slog.i(TAG, "Entered the Android system server!");
        Thread thr = new ServerThread();
        thr.setName("android.server.ServerThread");
        thr.start(); //执行serverThread的run方法
    }


在run方法中 创建了系统服务对象 通过ServiceManager保存起来

.....//声明各种服务
Installer installer = null;
       AccountManagerService accountManager = null;
       ContentService contentService = null;
       LightsService lights = null;
       PowerManagerService power = null;
       DisplayManagerService display = null;
       BatteryService battery = null;
       VibratorService vibrator = null;
        AlarmManagerService alarm = null;
        MountService mountService = null;
        NetworkManagementService networkManagement = null;
        NetworkStatsService networkStats = null;
        NetworkPolicyManagerService networkPolicy = null;
        ConnectivityService connectivity = null;
        WifiP2pService wifiP2p = null;
        WifiService wifi = null;
        NsdService serviceDiscovery= null;
//创建服务 通过ServiceManager管理 以key-value的形式添加到ServiceManger中
//所以 getSystemService(传入一个字符串) 返回服务 


            Slog.i(TAG, "Power Manager");
            power = new PowerManagerService();
            ServiceManager.addService(Context.POWER_SERVICE, power);

            Slog.i(TAG, "Activity Manager");
            context = ActivityManagerService.main(factoryTest);

            Slog.i(TAG, "Display Manager");
            display = new DisplayManagerService(context, wmHandler, uiHandler);
            ServiceManager.addService(Context.DISPLAY_SERVICE, display, true);

            Slog.i(TAG, "Telephony Registry");
            telephonyRegistry = new TelephonyRegistry(context);
            ServiceManager.addService("telephony.registry", telephonyRegistry);

            Slog.i(TAG, "Scheduling Policy");
            ServiceManager.addService(Context.SCHEDULING_POLICY_SERVICE,
                    new SchedulingPolicyService());


当所有的服务都添加进去之后 会执行ActivityManagerService的systemready方法

mMainStack.resumeTopActivityLocked(null);//判断当前的主任务栈是否有activity 如果没有就启动桌面


final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
       // Find the first activity that is not finishing.
       ActivityRecord next = topRunningActivityLocked(null);

       // Remember how we'll process this pause/resume situation, and ensure
       // that the state is reset however we wind up proceeding.
        final boolean userLeaving = mUserLeaving;
        mUserLeaving = false;

        if (next == null) {
            // There are no more activities!  Let's just start up the
            // Launcher...
            if (mMainStack) {
                ActivityOptions.abort(options);
                return mService.startHomeActivityLocked(mCurrentUser);
            }
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值