How to start the Android App application of source code interpretation?

foreword

As an Android developer for many years, I have written a lot of applications, but how does an App start? If you say that the desktop starts with a click, that's right. But what about its startup process? With such questions, let's learn step by step.

Android boot process

Generally on any platform, the following components are loaded and executed incrementally:

  • Boot loader
  • U-boot (optional)
  • Kernel
  • Android

Android processes have the following order:

  • Init
  • Zygote
  • System Server
  • Service Manager
  • Other Daemons and processes
  • Applications

The specific situation is as follows, and it is interesting to combine these two pictures:

image.png

  • Boot ROM : When the power is pressed, the boot chip code will start to execute from a predefined place (solidified in ROM), load the boot program BootLoader to RAM, and then execute. (This step is designed and implemented by the "chip manufacturer")

  • Boot loader : Bootloader starts to execute, first of all, it is responsible for completing the initialization of the hardware and booting the operating system to start. (This step is designed and implemented by the "equipment manufacturer")

  • Kernel : The Linux kernel is the core of Android, responsible for process creation, inter-process communication, device drivers, file system management, etc. Android applies custom patches on the mainstream kernel to support certain features required for Android to run, such as wakelocks. Kernels can be loaded as uncompressed or compressed images. On load, it mounts the root filesystem (usually passed as a kernel command line argument) and starts the first application in user space . (This step is what needs to be involved in the Android kernel development process)

  • Android : Android system and major Linux distributions, their Linux kernel part of the boot process is similar, the biggest difference between them is the difference in the init program, because the init program determines the system during the startup process. Which daemons and services are started, and what kind of UI is presented.

Therefore, the init program is the most core program in analyzing the Android startup process.

  • init and init.rc : The first user-space application executed when the kernel is started is the init executable located in the root folder. The process parses a startup script called the "init.rc" script. This is written in a language designed for android to start all necessary processes, daemons and services for android to function properly. It provides various types of execution times such as early-init, on-boot, on-post-fs, etc. (the originator of user space)

  • Demons and Services : The init process creates various daemons and processes, such as rild, vold, mediaserver, adb, etc., each process is responsible for its own functions. A description of these processes is beyond the scope of this article. Instead, we'll talk more about the "Zygote" process.

  • Service Manager : The Service Manager process manages all the Services running in the system. Every service created registers itself in this process and this information is for future reference by other processes/applications.

  • Zygote : Zygote is one of the first init processes created at startup. The term "zygote" is based on the biological "formation of an initial cell division to produce offspring". Similarly, "zygote in android" initializes the Dalivik VM (ART) and forks to create multiple instances to support each android process. It facilitates the use of shared code between VM instances, reducing memory footprint and load time, making it ideal for embedded systems. In addition to installing a listener on the server socket, Zygote also preloads classes and resources for later use in the Android application. After completion, the system server starts.

  • System Server : The SystemServer process starts all services available in Android.

In this article, we focus on starting from init to application startup.

1. What is Zygote?

In the Android system, zygote is the name of a process. Android is based on the Linux System. When your phone is turned on, a process called "init" will be started after the Linux kernel is loaded. In the Linux System, all processes are forked by the init process , and our zygote process is no exception.

Zygote is a virtual machine process and an incubator of virtual machine instances. Whenever the system requests to execute an Android application, Zygote will fork (split) a child process to execute the application.

1.1 app_main.cpp

frameworks/base/cmds/app_process/app_main.cpp

app_main.cpp is executed after Zygote starts. Whether it is C/c++/java, their entry is main(), just like when we see Activity, we directly look for the onCreate() method.

1.1.1 main()

int main(int argc, char* const argv[])
{
    ...
    //注释1:初始化AppRuntime(AndroidRunTime)
    AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
    ...
    // Parse runtime arguments.  Stop at first unrecognized option.
    bool zygote = false;
    bool startSystemServer = false;
    bool application = false;
    String8 niceName;
    String8 className;

    ++i;  // Skip unused "parent dir" argument.
    while (i < argc) {
        const char* arg = argv[i++];
        //注释2:设置zygote模式
        if (strcmp(arg, "--zygote") == 0) {
            zygote = true;
            niceName = ZYGOTE_NICE_NAME;
        } 
        ...
    }
    Vector<String8> args;
    if (!className.isEmpty()) {
        ...
    } else {
        // 我们处于 zygote 模式。
        maybeCreateDalvikCache();

        // 注释3:在 zygote 模式下,将参数传递给 ZygoteInit.main() 方法。
        if (startSystemServer) {
            args.add(String8("start-system-server"));
        }

        //PROP_VALUE_MAX = 92;
        char prop[PROP_VALUE_MAX];
        ...
        String8 abiFlag("--abi-list=");
        abiFlag.append(prop);
        args.add(abiFlag);

        for (; i < argc; ++i) {
            args.add(String8(argv[i]));
        }
    }    
    if (zygote) {
        //注释4:调用 AndroidRuntime.start() 方法
        runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
    } else if (className) {
        ...
    } else {
        ...
    }
}

Note 1: Initialize AppRuntime, which is actually AndroidRuntime (ART).

Note 2: Set zygote mode.

Note 3: Pass parameters to the ZygoteInit.main() method.

Note 4: Start ZygoteInit. ZygoteInit here is the startup class of the zygote process. This is mentioned below. Let's first look at the start() method of AndroidRuntime.

1.2 AndroidRuntime.cpp

frameworks/base/core/jni/AndroidRuntime.cpp

Android virtual machine

1.2.1 start()

/*
 * Start the Android runtime.  This involves starting the virtual machine and calling the "static void main(String[] args)" method in the class named by "className".
 *
 * Passes the main function two arguments, the class name and the specified
 * options string.
 */
void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
{
    ...
    JniInvocation jni_invocation;
    jni_invocation.Init(NULL);
    JNIEnv* env;
    //注释1:启动虚拟机
    if (startVm(&mJavaVM, &env, zygote, primary_zygote) != 0) {
        return;
    }
    onVmCreated(env);

    //注释2:注册安卓功能(JNI)
    if (startReg(env) < 0) {
        ALOGE("Unable to register all android natives\n");
        return;
    }
    ...
    strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
    ...
    /*
     * 启动虚拟机。 该线程成为VM的主线程,直到VM退出才会返回。
     */
    char* slashClassName = toSlashClassName(className != NULL ? className : "");
    jclass startClass = env->FindClass(slashClassName);
    if (startClass == NULL) {
        ...
    } else {
        ...
        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
            "([Ljava/lang/String;)V");
        if (startMeth == NULL) {
            ...
        } else {
            //注释3
            env->CallStaticVoidMethod(startClass, startMeth, strArray);
            if (env->ExceptionCheck())
                threadExitUncaughtException(env);
        }
    }
    ...
}
复制代码

Note 1: Start the VM (Virtual Machine)

Note 2: Registering Android Functions (JNI)

Note 3: Use JNI to call the main() method of Zygotelnit. Zygotelnit here is a class file, that is to say, it enters the java field from here.

JNI: A bridge connecting the native (C/C++) layer and the java layer.

1.3 ZygoteInit.java

frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

/**
 * zygote 进程的启动类。
 */
public class ZygoteInit {
    ...
}
复制代码

This is the entry point for the Zygote process. It creates Zygote services, loads resources, and handles other tasks related to the process of preparing for forking into an application.

1.3.1 main()

    @UnsupportedAppUsage
    public static void main(String[] argv) {
        ZygoteServer zygoteServer = null;

        try {
            ...
            boolean startSystemServer = false;
            //argv:用于指定 Zygote 配置的命令行参数。
            ...
            if (!enableLazyPreload) {
                //注释1:预加载资源。
                preload(bootTimingsTraceLog);
                EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                        SystemClock.uptimeMillis());
                bootTimingsTraceLog.traceEnd(); // ZygotePreload
            }
            ...
            //注释2:创建Zygote 的 LocalServerSocket 。
            zygoteServer = new ZygoteServer(isPrimaryZygote);

            if (startSystemServer) {
                //注释3:开始fork我们的SystemServer进程。
                Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
                ...
            }
            ...
            // 注释4:zygote 永久循环。
            caller = zygoteServer.runSelectLoop(abiList);            
        } catch (Throwable ex) {
            ...
        } finally {
            if (zygoteServer != null) {
                zygoteServer.closeServerSocket();
            }
        }
        ...
    }
复制代码

Note 1: Preload resources.

Note 2: Create Zygote's LocalServerSocket.

Note 3: Begin to fork our SystemServer process.

Note 4: zygote loops forever.

Here we look at forkSystemServer();

1.3.2 forkSystemServer ()

    /**
     * Prepare the arguments and forks for the system server process.
     *
     * @return A {@code Runnable} that provides an entrypoint into system_server code in the child
     * process; {@code null} in the parent.
     */
    private static Runnable forkSystemServer(String abiList, String socketName,
            ZygoteServer zygoteServer) {
        ...
        //命令行来启动SystemServer
        //ZygoteInit.main(String argv[])里面的argv 跟这个类似
        String[] args = {
                "--setuid=1000",
                "--setgid=1000",
                "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,"
                        + "1024,1032,1065,3001,3002,3003,3006,3007,3009,3010,3011",
                "--capabilities=" + capabilities + "," + capabilities,
                "--nice-name=system_server",
                "--runtime-args",
                "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
                "com.android.server.SystemServer",
        };
        //处理与 zygote spawner 相关的 args 的参数解析。
        ZygoteArguments parsedArgs;
        int pid;
        try {
            ZygoteCommandBuffer commandBuffer = new ZygoteCommandBuffer(args);
            try {
                parsedArgs = ZygoteArguments.getInstance(commandBuffer);
            } catch (EOFException e) {
                throw new AssertionError("Unexpected argument error for forking system server", e);
            }
            commandBuffer.close();
            ...

            //请求 fork 系统服务器进程
            /* Request to fork the system server process */
            pid = Zygote.forkSystemServer(
                    parsedArgs.mUid, parsedArgs.mGid,
                    parsedArgs.mGids,
                    parsedArgs.mRuntimeFlags,
                    null,
                    parsedArgs.mPermittedCapabilities,
                    parsedArgs.mEffectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }

        /* For child process */
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }

            zygoteServer.closeServerSocket();
            return handleSystemServerProcess(parsedArgs);
        }

        return null;
    }
复制代码

A system server is started here. Let's take a look at him below.

2、SystemServer

system server is also SystemServer. SystemServer is also a process, including 92 services such as ActivityTaskManagerService, ActivityManagerService, PackageManagerService, and WindowManagerService.

There are two very important processes in the Android Framework:

  • SystemServer process.

  • Zygote process.

2.1 SystemServer.java

frameworks/base/services/java/com/android/server/SystemServer.java

public final class SystemServer {
    ...
}
复制代码

2.1.1 main()

    /**
     * The main entry point from zygote.
     */
    public static void main(String[] args) {
        new SystemServer().run();
    }
    public SystemServer() {
        // Check for factory test mode.
        mFactoryTestMode = FactoryTest.getMode();
        ...
    }    
复制代码

Let's take a look at what is used in run ()?

2.1.2 run()

    private void run() {
        try {
            ...
            // 注释1:加载动态库libandroid_service.so。
            System.loadLibrary("android_servers");

            // 注释2:创建系统上下文。
            createSystemContext();

            // 调用每个进程的主线模块初始化。
            ActivityThread.initializeMainlineModules();

            // 注释3:创建 SystemServiceManager。
            mSystemServiceManager = new SystemServiceManager(mSystemContext);
            mSystemServiceManager.setStartInfo(mRuntimeRestart,
                    mRuntimeStartElapsedTime, mRuntimeStartUptime);
            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
            // 为可并行化的 init 任务准备线程池
            SystemServerInitThreadPool.start();
            ...
        } finally {

        }
        // 注释4:Start services。
        try {
            //下面咱们看看这个三个方法启动什么服务
            startBootstrapServices(t);
            startCoreServices(t);
            startOtherServices(t);
        } catch (Throwable ex) {
            ...
        } finally {
            t.traceEnd(); // StartServices
        }

        ...
        // 注释5:Loop 永久循环。
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

复制代码

Note 1: Load the dynamic library libandroid_service.so.

Note 2: Create a system context.

Note 3: Create SystemServiceManager.

Note 4: Start Services (startBootstrapServices, startCoreServices, startOtherServices)

Note 5: Loop loops forever.

2.1.3 createSystemContext()

    private void createSystemContext() {
        ActivityThread activityThread = ActivityThread.systemMain();
        mSystemContext = activityThread.getSystemContext();
        mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

        final Context systemUiContext = activityThread.getSystemUiContext();
        systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
    }
复制代码

Initialize the system context object mSystemContext, and set the default theme, mSystemContext is actually a Context (ContextImpl) object.

When ActivityThread.systemMain() is called, ActivityThread.attach(true) is called, and in attach(), the Application object is created and Application.onCreate() is called.

2.1.4 startBootstrapServices()

    /**
     * 启动系统引导服务,因为这些服务之间有复杂的相互依赖关系,所以都放在了这个方法里面。
     */
    private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
        ...
        final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
        SystemServerInitThreadPool.submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);

        // PlatformCompat Service 由 ActivityManagerService, PackageManagerService 和 其他服务做使用
        PlatformCompat platformCompat = new PlatformCompat(mSystemContext);
        ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE, platformCompat);
        ServiceManager.addService(Context.PLATFORM_COMPAT_NATIVE_SERVICE,
                new PlatformCompatNative(platformCompat));
        AppCompatCallbacks.install(new long[0]);

        mSystemServiceManager.startService(FileIntegrityService.class);
        Installer installer = mSystemServiceManager.startService(Installer.class);
        mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
        mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);
        startMemtrackProxyService();

        // StartActivityManager
        ActivityTaskManagerService atm = mSystemServiceManager.startService(
                ActivityTaskManagerService.Lifecycle.class).getService();
        //初始化 ActivityManagerService
        mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                mSystemServiceManager, atm);
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);
        mWindowManagerGlobalLock = atm.getGlobalLock();

        mDataLoaderManagerService = mSystemServiceManager.startService(
                DataLoaderManagerService.class);

        mIncrementalServiceHandle = startIncrementalService();
        t.traceEnd();

        //初始化PowerManagerService(电源服务),需要提前启动,因为其他服务需要它。
        mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
        mSystemServiceManager.startService(ThermalManagerService.class);

        // 电源管理已经开启,ActivityManagerService负责电源管理功能
        mActivityManagerService.initPowerManagement();

        mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);
        ...

        mSystemServiceManager.startService(LightsService.class);

        // Package manager isn't started yet; need to use SysProp not hardware feature
        if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
            mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
        }

        // 初始化DisplayManagerService(显示管理器)
        mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

        mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

        // Start the package manager.
        try {
            mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                    mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
        } finally {

        }

        // 现在PackageManagerService已经启动,注册 dex 加载报告器来捕获系统服务加载的任何 dex 文件。
        // 这些 dex 文件将由 BackgroundDexOptService 优化。
        SystemServerDexLoadReporter.configureSystemServerDexReporter(mPackageManagerService);

        mFirstBoot = mPackageManagerService.isFirstBoot();
        mPackageManager = mSystemContext.getPackageManager();
        ...
        //将AMS等添加到ServiceManager中
        mActivityManagerService.setSystemProcess();
        if (!mOnlyCore) {
            boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
                    false);
            if (!disableOtaDexopt) {
                try {
                    OtaDexoptService.main(mSystemContext, mPackageManagerService);
                } catch (Throwable e) {

                } finally {
                }
            }
        }

        ...
        mSensorServiceStart = SystemServerInitThreadPool.submit(() -> {
            TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
            startSensorService();
        }, START_SENSOR_SERVICE);

        // startBootstrapServices
    }
复制代码

Major changes:

  • ActivityTaskManagerService(ATMS): Responsible for managing activities and processes, including life cycle and state switching.

  • ActivityManagerService (AMS): A subclass of AMN, responsible for managing three major components (except Activity) and processes, including life cycle and state switching. AMS is extremely complex because it has to interact with the ui, involving windows.

ActivityTaskManagerService: Generated by stripping Activity-related content from ActivityManagerService.

PowerManagerService(PMS): Power management service.

PackageManagerService(PKMS): The package management service, not called PMS, is to distinguish it from the power management service.

2.1.5 startCoreServices()

    /**
     * 启动核心服务。
     */
    private void startCoreServices(@NonNull TimingsTraceAndSlog t) {
        // Service for system config
        mSystemServiceManager.startService(SystemConfigService.class);
        // Tracks the battery level.  Requires LightService.
        mSystemServiceManager.startService(BatteryService.class);
        ...
        mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);

        mSystemServiceManager.startService(ROLLBACK_MANAGER_SERVICE_CLASS);

        mSystemServiceManager.startService(NativeTombstoneManagerService.class);

        mSystemServiceManager.startService(BugreportManagerService.class);

        mSystemServiceManager.startService(GpuService.class);

        // startCoreServices
    }

复制代码

2.1.6 startOtherServices()

    /**
     * 启动其他服务。
     */
    private void startOtherServices(@NonNull TimingsTraceAndSlog t) {

        final Context context = mSystemContext;
        VibratorService vibrator = null;
        DynamicSystemService dynamicSystem = null;
        IStorageManager storageManager = null;
        NetworkManagementService networkManagement = null;
        IpSecService ipSecService = null;
        VpnManagerService vpnManager = null;
        VcnManagementService vcnManagement = null;
        NetworkStatsService networkStats = null;
        NetworkPolicyManagerService networkPolicy = null;
        NsdService serviceDiscovery = null;
        WindowManagerService wm = null;
        SerialService serial = null;
        NetworkTimeUpdateService networkTimeUpdater = null;
        InputManagerService inputManager = null;
        TelephonyRegistry telephonyRegistry = null;
        ConsumerIrService consumerIr = null;
        MmsServiceBroker mmsService = null;
        HardwarePropertiesManagerService hardwarePropertiesService = null;
        PacProxyService pacProxyService = null;
        ...
        // 现在便可以开始启动三方APP应用(如Launcher启动桌面)
        mActivityManagerService.systemReady(() -> {
        ...
         }, t);       
        // startOtherServices
    }
复制代码

After the above steps, when we call createSystemContext() to create the system context, we have completed the creation of mSystemContext and ActivityThread.

Objects such as ATMS, AMS, WMS, and PKMS have been created, and member variables have been initialized.

Note: This is the process when the system process is started. After that, the system will be started.

The Launcher program completes the loading and display of the system interface.

In the framework design of Android, the server side refers to the system services shared by all apps, such as ATMS, AMS, WMS, PKMS, etc. we mentioned here. These basic system services are shared by all apps.

3. What is Launcher

In the Android system, the application is started by the Launcher. In fact, the Launcher itself is also an application . After other applications are installed, a corresponding icon will appear on the Launcher interface. When this icon is clicked, the Launcher will The corresponding application starts up.

Of course, you can also start applications in other applications. But in essence it calls startActivity().

3.1 LauncherActivity.java

frameworks/base/core/java/android/app/LauncherActivity.java

/**
 * Displays a list of all activities which can be performed
 * for a given intent. Launches when clicked.
 *
 * @deprecated Applications can implement this UI themselves using
 *   {@link androidx.recyclerview.widget.RecyclerView} and
 *   {@link android.content.pm.PackageManager#queryIntentActivities(Intent, int)}
 */
@Deprecated
public abstract class LauncherActivity extends ListActivity {
    ...
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Intent intent = intentForPosition(position);
        startActivity(intent);
    }
}
复制代码

summary

A full picture is attached

If you know about startActivity(), you can take a look directly. There's so much content in this post that I'm irritated just looking at it. If you haven't seen it, take a wave, and the details will be explained in the next article: ❤️ Android startActivity source code analysis ❤️.

Guess you like

Origin blog.csdn.net/ajsliu1233/article/details/120711444