Android application startup process: from startup to interactive process analysis

About the author: CSDN content partner, technical expert, starting from scratch to make tens of millions of daily activities APP.
Focus on sharing original series of articles in various fields, good at java backend, mobile development, artificial intelligence, etc. I hope you will support me a lot.

insert image description here

1. Introduction

We continue to summarize and learn the basics of Android , reviewing the past and learning the new.

When I was doing system application development many years ago, I learned the startup process of APP by compiling the source code.
Recently, I am sorting out the documents related to application startup optimization. I plan to reorganize them and organize them into an easy-to-understand document for later Check.
In the learning process, it is best to download the source code.

1.1 Start knowledge reserve

The start-up process is relatively complicated and involves a lot of knowledge points. It is recommended to learn through other articles.

1.2 Zygote process

The Zygote process is created and started by the init process when the Android device starts, and then continuously receives requests from applications.
The Zygote process pre-creates a virtual machine and some shared resources to improve the startup speed of applications and the utilization efficiency of system resources.
At the same time, the Zygote process is also responsible for processing the environment initialization of the application process and loading the core class library.
Whenever a new application start request arrives, the Zygote process will fork a child process (application process) to run the application.

1.3 SystemServer process

The SystemServer process is a key process of the Android operating system, which is created by the init process when the device starts.

The SystemServer process is a daemon process that always exists during system operation and is responsible for starting and managing various core system services , such as AMS, Window Manager, Package Manager, etc.

1.4 AMS(Activity Manager Service)

AMS (Activity Manager Service) is a key component in the SystemServer process, responsible for managing the life cycle and interaction of all applications . It monitors application startup, suspension, resumption, and destruction,
and coordinates switching and interaction between applications. In addition, AMS also handles related tasks such as task stack management, rights management, and user notification.

1.5 APP process (ActivityThread)

The APP process refers to the application process running in the Android system. Each running application will allocate one or more independent APP processes to host the execution environment of the application.
Each APP process is a child process created by the Zygote process through the fork system call.

ActivityThread is the main thread of the Android application, responsible for managing and scheduling the life cycle of all activities in the application and handling some system events.

The main responsibilities of ActivityThread include:

  1. Create and start the application's main Activity.
  2. Handles the application's message loop, receiving and dispatching messages from the system and the application.
  3. Manage the life cycle of all activities in the application, including creating, starting, suspending, resuming, stopping, and destroying.
  4. Handle the resource loading and updating of the application, including the loading of resources such as layout files, pictures, and strings.
  5. Handles the application's window management, including operations such as creating, showing, hiding, and updating windows.
  6. Communicate with AMS (Activity Manager Service), process Activity start, stop, switch and other requests, and receive instructions and requests from AMS.
  7. Handle abnormal errors of the application, including crashes, ANR (Application Not Responding) and other situations.

2. Overview of the startup process

Communication between multiple processes is involved:
1. After the user clicks the icon, Laucher (mobile desktop) will notify the SystemServer process through the binder.
2. SystemServer receives the information, and the internal AMS (Activity Manager Service) notifies Zygote to create an APP process, and calls the ActivityThread.main method through reflection, that is, creates the main thread.
3. After the APP process is created (Zygote performs fork), AMS is notified through a callback.
4. After receiving the information, AMS informs the APP process (ActivityThread) to create the Application through a series of calls.
5. After the Application, it continues to call the ClientLifecycleManager to create the Activity and other processes.

Let's draw a simple picture
picture
insert image description here

Paste the code below:

2.1 The user clicks the desktop icon

Launcher obtains the binder of AMS, and then enters the SystemServer process.

Then call the zygote process to fork a new app process.

2.2 Create app process

ActivityThread


应用进程启动的入口函数main()方法中,会调用Looper相关的初始化和循环方法,从而让主线程的Looper进入循环状态,保证app进程的一直运行状态

    public static void main(String[] args) {
    
    
        . ..
        //looper绑定主线程
        Looper.prepareMainLooper();
        
        创建ActivityThread
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

        
        //looper开启无限循环读取消息
        Looper.loop();

            . ..
    }


    private void attach(boolean system, long startSeq) {
    
    
        
        if (!system) {
    
    
            . ..
            final IActivityManager mgr = ActivityManager.getService();
            try {
    
    
                // 通知 AMS, 并将当前进程的binder句柄传给AMS绑定管理起来
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
    
    
            }
            . ..
        }
        
        . ..
    }

attachApplication This process will be divided into two steps:
1. Create the application object of the application
2. Activity start display

2.3 create application

IActivityManager.aidl


    void attachApplication(in IApplicationThread app, long startSeq);

ActivityManagerService


// 这里接受APP传递过来的消息
    @Override
    public final void attachApplication(IApplicationThread thread, long startSeq) {
    
    
        synchronized (this) {
    
    
            // 通过 Binder 获取 PID ,PID和UID都是进程创建应用的时候系统指定的
            int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();
            final long origId = Binder.clearCallingIdentity();
            
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        }
    }


    @GuardedBy("this")
    private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid, int callingUid, long startSeq) {
    
    

    
        // *** 1、通知APP进程进行初始化操作,初始化application,创建应用进程的application对象
        if (app.isolatedEntryPoint != null) {
    
    
                
        } else if (app.instr != null) {
    
    
            thread.bindApplication(processName, appInfo, providers, ...);
        } else {
    
    
            thread.bindApplication(processName, appInfo, providers, ...);
        }

        
        // *** 2、 通知APP拉起指定的MainActivity,调用ATMS的启动页面的方法,后面继续介绍
        // See if the top visible activity is waiting to run in this process...
        if (normalMode) {
    
    
            try {
    
    
                if (mStackSupervisor.attachApplicationLocked(app)) {
    
    
                    didSomething = true;
                }
            } catch (Exception e) {
    
    
            }
        }
    }

IApplicationThread.aidl


void bindApplication(in String packageName, in ApplicationInfo info, ...);

Let's take a look at how Application is created
ActivityThread

AMS调用过来,具体看上面的代码
public final void bindApplication(String processName, ApplicationInfo appInfo, ...) {
    
    

        sendMessage(H.BIND_APPLICATION, data);
}

public void handleMessage(Message msg) {
    
    
    
    switch (msg.what) {
    
    
        case BIND_APPLICATION:
            
        AppBindData data = (AppBindData)msg.obj;
        handleBindApplication(data);
        break;
        
        . ..
    }
}


private void handleBindApplication(AppBindData data) {
    
    

    Application app;
    try{
    
    
        classLoader加载APK中的dex,并且加载APK的资源
        final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
                appContext.getClassLoader(), false, true, false);
        final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);

        通过 calssLoader 来创建 application 对象
        app=data.info.makeApplication(data.restrictedBackupMode,null);


        try{
    
    
            调用Application的onCreate
        
            mInstrumentation.onCreate(data.instrumentationArgs);
        }catch(Exception e){
    
    
        }
        try{
    
    
            mInstrumentation.callApplicationOnCreate(app);
        }catch(Exception e){
    
    

        }
    } ... 
}


public Application newApplication(ClassLoader cl, String className, Context context) 。。{
    
    
    Application app = getFactory(context.getPackageName()).instantiateApplication(cl, className);
    app.attach(context);
    return app;
}


(Application) cl.loadClass(className).newInstance();

insert image description here

2.4 activity startup display

Then the above code mStackSupervisor.attachApplicationLocked(app);

ActivityStackSupervisor
方法realStartActivityLocked();


    boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
    
    
        final String processName = app.processName;
        boolean didSomething = false;
            
        
        Activity启动的入口
        try {
    
    
            if (realStartActivityLocked(activity, app, top == activity, true)) {
    
    
                
            }
        } catch (RemoteException e) {
    
    
        }
        return didSomething;
    }

    真的开始启动 activity
    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
    
    

            // Create activity launch transaction.
            final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                    r.appToken);
                    clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                    System.identityHashCode(r), r.info,
                    // TODO: Have this take the merged configuration instead of separate global
                    // and override configs.
                    mergedConfiguration.getGlobalConfiguration(),
                    mergedConfiguration.getOverrideConfiguration(), r.compat,
                    r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                    r.persistentState, results, newIntents, mService.isNextTransitionForward(),
                    profilerInfo));
            
            // Schedule transaction.
            mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    }

ActivityManagerService


    ClientLifecycleManager getLifecycleManager() {
    
    
        return mLifecycleManager;
    }
    

ClientLifecycleManager

    通过代码,我们可以看到,获取的client就是 ActivityThreadIApplicationThread是一个AIDL文件
    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    
    
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();
        
    }

ClientTransaction

        
    /** Target client. */
    private IApplicationThread mClient;
    
    public void schedule() throws RemoteException {
    
    
        mClient.scheduleTransaction(this);
    }

ClientTransactionHandler


    //ActivityThread中没有复写scheduleTransaction,会执行到父类的方法
    //public final class ActivityThread extends ClientTransactionHandler
    //ClientTransactionHandler.java
    public abstract class ClientTransactionHandler {
    
    
    
        void scheduleTransaction(ClientTransaction transaction) {
    
    
            transaction.preExecute(this);
            //发送消息
            sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
        }
    }

ActivityThread.java


    case EXECUTE_TRANSACTION:
        final ClientTransaction transaction = (ClientTransaction) msg.obj;
        mTransactionExecutor.execute(transaction);
        break;
        

continue a series of calls
insert image description here

Finally, call to ActivityThread to create and start the Activity. Due to space reasons, we will introduce the content related to Activity resource loading in another article.


    /**
     * Extended implementation of activity launch. Used when server requests a launch or relaunch.
     */
    @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
    
    

        final Activity a = performLaunchActivity(r, customIntent);


        return a;
    }

    Activity实例化过程
    
    /**  Core implementation of activity launch. */
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    
    

        Activity activity = null;
        try {
    
    
            // 通过反射实例化Activity对象
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
        } catch (Exception e) {
    
    
        }
        
        window
            
        theme
        
        //当实例化Activity对象后,继续执行callActivityOnCreate
        if (r.isPersistable()) {
    
    
            mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
        } else {
    
    
            mInstrumentation.callActivityOnCreate(activity, r.state);
        }
    }

The next step is to execute the Activity life cycle function

The source code used is different, and the code may be slightly different.

3. Recommended reading

Java column

SQL column

Data Structures and Algorithms

Android Learning Column

Guess you like

Origin blog.csdn.net/fumeidonga/article/details/132146863