Android World first activity startup process

Source: Internet
Author: User

Android World first activity startup process

It feels good to use markdown for the first time.
Android system from pressing the Start button until the advent of launcher, is a kind of process, the middle of what has been done, with these questions to start the source of the journey.
Like the Windows operating system, every system starts with a boot program, and in Linux, when the boot loader starts the Linux kernel, it loads a variety of drivers and data structures, and when the driver starts loading the android system, Start the first process into the Linux world: the init process.

In the main of init.c:
    int main(int argc, char **argv){            umask(0);// 清除文件的默认属性            mkdir("/dev", 0755); // 创建文件、挂载文件等操作            ........            init_parse_config_file("/init.rc");  // 解析文件            .........    }
In the Init.rc file: (the file is in the System/core/rootdir directory)
    // 设置一些全局环境变量    export PATH /sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin    export LD_LIBRARY_PATH /vendor/lib:/system/lib    ..............    // 创建基本的文件系统结构    mkdir /data/misc 01771 system misc    ..............    // 启动一些服务    service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server    socket zygote stream 666    onrestart write /sys/android_power/request_state wake    onrestart write /sys/power/state on    onrestart restart media    onrestart restart netd    .............

The most important is this zygote process, zygote is an incubator, similar to the parent process, can fork out a lot of sub-processes, is a parent process of Android, used to launch other Android service processes. The zygote process automatically restarts these service processes when the media, NETD, and other service processes are destroyed

In the App_main.cpp file:
    int main(int argc, const char* const argv[]){            ............................             bool startSystemServer = (i < argc) ?              strcmp(argv[i], "--start-system-server") == 0 : false;             setArgv0(argv0, "zygote");            set_process_name("zygote");            runtime.start("com.android.internal.os.ZygoteInit",startSystemServer);    }
In the Start method of the Androidruntime
  void Androidruntime::start (const char* className, const bool startsystemserver) {...... ...//Open the Java Virtual machine and load the JNI run environment if (STARTVM (&MJAVAVM, &env)! = 0) Goto bail            ;            ...//Use JNI to interact with Java to load the Zygoteinit class Startclass = Env->findclass (slashclassname);            if (Startclass = = NULL) {LOGE ("JAVAVM Unable to locate class '%s ' \ n", slashclassname); } else {///use JNI to invoke the Main method in the Zygoteinit class Startmeth = Env->getstaticmethodid (Startclass, "Ma                In "," ([ljava/lang/string;) V ");            if (Startmeth = = NULL) {LOGE ("JAVAVM Unable to find main () in '%s ' \ n", className);                } else {Env->callstaticvoidmethod (Startclass, Startmeth, Strarray);            if (Env->exceptioncheck ()) threadexituncaughtexception (env); }    }
In the Zygoteinit.java:
    public static void Main (String argv[]) {//sets the minimum heap size for Android runtime 5M Vmruntime.getruntime (). Setminim            Umheapsize (5 * 1024 * 1024);             ...//pre-load some commonly used classes, these commonly used classes in 2.3 has about 1800, in 4.2 of the source code is probably more than 2,400 commonly used//like some mobile phone manufacturers mobile phone startup faster, is estimated to be optimized here            Preloadclasses ();            Load some resource files, array, drawable, color and other XML files preloadresources ();                    ... if (Argv[1].equals ("true")) {//Fork the system service process in the Systemserver class             Startsystemserver ();             } else if (!argv[1].equals ("false")) {throw new RuntimeException (Argv[0] + usage_string); }} private static Boolean Startsystemserver () throws Methodandargscaller, RuntimeException {String A            Rgs[];            String ashmem_size = System.getproperty ("Gralloc.ashmem_size"); if ((null! = ashmem_size) && (0! = Ashmem_size.length ())) {args = new string[] {"--setuid=1000", "--setgid=1000", "--setgroups=1001,1002,1003                    , 1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003,3006 ","--capabilities=130104352,130104352 ",                    "--rlimit=8," "--runtime-init", "--nice-name=system_server",                "Com.android.server.SystemServer",};                ARGS[4] = Args[4].concat (ashmem_size);                ARGS[4] = Args[4].concat (",");            ARGS[4] = Args[4].concat (ashmem_size);                    } else {args = new string[] {"--setuid=1000", "--setgid=1000",                    "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003,3006", "--capabilities=130104352,130104352", "--runtime-init", "--nice-name=system_server "," Com.android.sErver.            Systemserver ",}; } .... pid = Zygote.forksystemserver (Parsedargs.uid, Parse, .....) ..... = = = = = =/-                Dargs.gid, Parsedargs.gids, DebugFlags, Rlimits, Parsedargs.permittedcapabilities,    Parsedargs.effectivecapabilities);    } catch (IllegalArgumentException ex) {throw new RuntimeException (ex); }
In the Systemserver class:
     native public static void init1(String[] args);             .........             System.loadLibrary("android_servers");             init1(args);             .........     }
First load android_servers This so library, this library is systemserver the parent directory under the same level of the JNI directory, the corresponding C file is com_android_server_systemserver.c. Then call the Init1 method in the library,
     extern "C" int system_init();    static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)    {        system_init();    }    static JNINativeMethod gMethods[] = {        { "init1", "([Ljava/lang/String;)V", (void*) android_server_SystemServer_init1 },    };
int register_android_server_SystemServer(JNIEnv* env){return jniRegisterNativeMethods(env, "com/android/server/SystemServer",        gMethods, NELEM(gMethods));}
We can see that init1 is registered to the Android_server_systemserver_init1 method, and the System_init method is called in the Android_server_systemserver_init1 method, This method appears in the System_init.cpp.
extern "C" status_t system_init(){// 开启传感器服务SensorService::instantiate();if (!proc->supportsProcesses()) {    AudioFlinger::instantiate();    // 启动媒体播放服务    MediaPlayerService::instantiate();    CameraService::instantiate();    AudioPolicyService::instantiate();}  // 启动Android运行时AndroidRuntime* runtime = AndroidRuntime::getRuntime();.................runtime->callStatic("com/android/server/SystemServer", "init2");.................return NO_ERROR;
In the System_init () method in the System_init.cpp class: Using runtime to invoke Systemserver's Init2 method, the Init2 method is described as follows:
public static final void init2() {    // 开始进入Android系统服务    Thread thr = new ServerThread();    thr.setName("android.server.ServerThread");    thr.start();}
In the Run method:
...........// 实例化各种系统服务ContentService.main(context,factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);Slog.i(TAG, "System Content Providers");ActivityManagerService.installSystemProviders();Slog.i(TAG, "Battery Service");battery = new BatteryService(context);ServiceManager.addService("battery", battery);Slog.i(TAG, "Lights Service");lights = new LightsService(context);............ServiceManager.addService("vibrator", new VibratorService(context));    ............ ((ActivityManagerService)ActivityManagerNative.getDefault())            .systemReady(new Runnable() {        public void run() {            ........        });
Serverthread thread tasks are primarily new out-of-system services and then added to ServiceManager Unified management, Mmainstack.resumetopactivitylocked (NULL) is executed in the Systemready method that last called Activitymanagerservice, or the first activity is opened.
  final boolean resumeTopActivityLocked(ActivityRecord prev) {    // 寻找没有被finish掉的第一个activity    ActivityRecord next = topRunningActivityLocked(null);    final boolean userLeaving = mUserLeaving;    mUserLeaving = false;    if (next == null) {        if (mMainStack) {            // 没有activity,启动launcher            return mService.startHomeActivityLocked();        }    }    .....................  }
The first activity in the Android world has been successfully launched, and it is the main activity in launcher.

Copyright NOTICE: This article for Bo Master original article, without BO Master permission cannot reprint (Contact: QQ312037487 Email: [Email protected]).

Android World first activity startup process

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.