android应用程序启动源码浅析-kb88凯时官网登录

来自:
时间:2024-06-05
阅读:
sequencediagram participant user participant launcher participant activitymanagerservice participant zygote participant appprocess participant application participant firstactivity user ->> launcher: 点击应用图标 launcher ->> activitymanagerservice: 请求启动activity activitymanagerservice ->> zygote: 创建新进程 zygote -->> appprocess: fork新进程 appprocess ->> application: 创建application实例 application ->> firstactivity: 启动第一个activity firstactivity ->> user: 显示界面

2.1 activity.java

  • 在中提到launcher最终通过frameworks/base/core/java/android/app/activity.java中的startactivity方法启动了对应的应用程序。
  • startactivity方法是通过调用startactivityforresult方法来实现的。
  • startactivityforresult方法最终调用了/frameworks/base/core/java/android/app/instrumentation.javaexecstartactivity方法
public class activity {
    @override
    public void startactivity(intent intent) {
        this.startactivity(intent, null);
    }
    @override
    public void startactivity(intent intent, @nullable bundle options) {
        if (options != null) {
            startactivityforresult(intent, -1, options);
        } else {
            startactivityforresult(intent, -1);
        }
    }
    
    @override
    public void startactivityforresult(...) {
        if (mparent == null) {
            options = transferspringboardactivityoptions(options);
            // 调用instrumentation的execstartactivity方法
            instrumentation.activityresult ar =
                minstrumentation.execstartactivity(...);
        }
    }
}

2.2 instrumentation.java

  • instrumentation.java中的execstartactivity方法是activity启动流程的关键。
  • execstartactivity方法通过activitytaskmanager.getservice().startactivity方法与系统服务进行通信.
// instrumentation中有多个execstartactivity同名方法,注意是target的类型为activity的方法
public activityresult execstartactivity(
        context who, ibinder contextthread, ibinder token, activity target,
        intent intent, int requestcode, bundle options) {
        
        // activitytaskmanager.getservice()获取到activitytaskmanagerservice的实例对象
        // 调用activitytaskmanagerservice.startactivity
        int result = activitytaskmanager.getservice()
                .startactivity(...);
}

2.3 activitytaskmanagerservice.java

  • activitytaskmanagerservice是一个系统服务,负责管理activity的启动。
  • startactivity方法调用了startactivityasuser方法
  • startactivityasuser方法通过activitystartcontrollerobtainstarter方法获取了activitystarter对象实例,并调用activitystarterexecute方法
  •  
public final int startactivity(...) {
    // 调用startactivityasuser方法
    return startactivityasuser(...);
}
public final int startactivityasuser(...) {
    // activitystartcontroller的obtainstarter获取了activitystarter对象
    return getactivitystartcontroller().obtainstarter(intent, "startactivityasuser")
                ... // 构造参数
                .execute();
}

2.4 activitystarter.java

  • activitystarter中最终会调用rootwindowcontainerresumefocusedtaskstopactivities方法
int execute() {
    // 调用executerequest方法
    res = executerequest(mrequest);
}
private int executerequest(request request) {
    // 创建activityrecord对象
    final activityrecord r = new activityrecord.builder(mservice)
            .setcaller(callerapp)
            ... // 构造参数
            .build();
    // 调用startactivityunchecked方法
    mlaststartactivityresult = startactivityunchecked(...);
}
private int startactivityunchecked(...) {
    // 调用startactivityinner
    result = startactivityinner(...);
}
int startactivityinner(...) {
    // 调用rootwindowcontainer的resumefocusedtaskstopactivities方法
    mrootwindowcontainer.resumefocusedtaskstopactivities(...);
}

2.5 rootwindowcontainer.java

  • rootwindowcontainer是windowmanagerservice的主要组成部分之一,是一个管理窗口的容器。
  • 调用tasktaskfragment将前台程序pause,为新的应用程序启动做准备。
  • resumefocusedtaskstopactivities中调用taskresumetopactivityuncheckedlocked方法。

private boolean resumefocusedtaskstopactivities(...) {
    // 调用task的resumetopactivityuncheckedlocked方法
    result = targetroottask.resumetopactivityuncheckedlocked(...);
}

2.5.1 task.java

  • task最终调用taskfragmentresumetopactivity方法
@guardedby("mservice")
boolean resumetopactivityuncheckedlocked(...) {
    // 调用resumetopactivityinnerlocked
    someactivityresumed = resumetopactivityinnerlocked(...);
}
@guardedby("mservice")
private boolean resumetopactivityinnerlocked(...) {
    final taskfragment topfragment = topactivity.gettaskfragment();
    // 调用taskfragment的resumetopactivity
    resumed[0] = topfragment.resumetopactivity(...););
    return resumed[0];
}

2.5.2 taskfragment.java

  • taskfragment最终调用activitytaskmanagerservicestartprocessasync方法
final boolean resumetopactivity(...) {
   // 暂停当前窗口的aciticity,可参见源码
   ...
   // 调用activitytaskmanagerservice的startprocessasync方法创建新的activity
activitytaskmanagerservice的startprocessasync方法
   matmservice.startprocessasync(...);
}

2.6 再次回到activitytaskmanagerservice.java

  • 处理完窗口容器数据以后(核心工作是将前台程序pause),再次回到了activitytaskmanagerservice
  • startprocessasync方法发送异步消息,调用activitymanagerinternalstartprocess方法
  • activitymanagerinternal的实现类是activitymanagerservice
// maminternal的获取方法,注册方法在activitymanagerservice中(下一小节2.8做介绍)
maminternal = localservices.getservice(activitymanagerinternal.class);
void startprocessasync(...) {
    
        // pooledlambda会自动调用maminternal(activitymanagerinternal)的startprocess方法
        final message m = pooledlambda.obtainmessage(activitymanagerinternal::startprocess, maminternal, ...);
        mh.sendmessage(m);
}
  • activitymanagerinternal是一个抽象类,具体实现在activitymanagerservice.java中实现

2.7 activitymanagerservice.java

  • activitymanagerservice最终调用processliststartprocesslocked方法
public class activitymanagerservice extends iactivitymanager.stub {
    
    // 初始化localservice(activitymanagerinternal)
    private final activitymanagerinternal minternal = new localservice();
    public void init() {
        // 在localservices中进行注册
        localservices.addservice(activitymanagerinternal.class, minternal);
    }
    private class localservice extends activitymanagerinternal {
        // activitymanagerinternal 接口方法的具体实现
        @override
        public void startprocess(...) {
            synchronized (activitymanagerservice.this) {
                // 调用activitymanagerservice的startprocesslocked方法
                startprocesslocked(...)
            }
        }
    }
        @guardedby("this")
    final processrecord startprocesslocked(...) {
        // 调用processlist的startprocesslocked
        return mprocesslist.startprocesslocked(...);
    }
}

2.7.1 processlist.java

  • processlist最终调用到zygoteprocessstart方法
@guardedby("mservice")
boolean startprocesslocked(processrecord app, ...) {
    // 定义创建activity完成后回调的入口点(重要)
    final string entrypoint = "android.app.activitythread";
    return startprocesslocked(hostingrecord, ...);
}
@guardedby("mservice")
boolean startprocesslocked(hostingrecord hostingrecord, ...) {
    // 调用startprocess
    final process.processstartresult startresult = startprocess(...);
}
private process.processstartresult startprocess(...) {
    // 获取appzygote
    final appzygote appzygote = createappzygoteforprocessifneeded(app);
    // appzygote.getprocess()获取到childzygoteprocess类(zygoteprocess的子类)
    // 调用zygoteprocess的start方法
    startresult = appzygote.getprocess().start(entrypoint,...);
}

2.8 zygoteprocess.java

  • zygoteprocess发送消息给zygote进程,通过zygote进程创建新的activity进程
public final process.processstartresult start(...) {
    // 调用startviazygote
    return startviazygote(...)
}
private process.processstartresult startviazygote(...) {
    // 通过openzygotesocketifneeded(abi)打开一个到zygote进程的套接字连接(socket)。
    // 调用zygotesendargsandgetresult
    return zygotesendargsandgetresult(openzygotesocketifneeded(abi),zygotepolicyflags,argsforzygote);
}
@guardedby("mlock")
private process.processstartresult zygotesendargsandgetresult(...) {
    // 调用attemptzygotesendargsandgetresult
    return attemptzygotesendargsandgetresult(...);
}
private process.processstartresult attemptzygotesendargsandgetresult(...) {
    try {
        // 创建zygote套接字的输入输出流
        final bufferedwriter zygotewriter = zygotestate.mzygoteoutputwriter;
        final datainputstream zygoteinputstream = zygotestate.mzygoteinputstream;
        // 发送消息给 zygote 进程
        zygotewriter.write(msgstr);
        zygotewriter.flush();
        // 读取 zygote 进程返回的结果
        process.processstartresult result = new process.processstartresult();
        result.pid = zygoteinputstream.readint();
        result.usingwrapper = zygoteinputstream.readboolean();
        // 检查 pid 是否有效
        if (result.pid < 0) {
            throw new zygotestartfailedex("fork() failed");
        }
        return result;
    } catch (ioexception ex) {
        zygotestate.close();
        log.e(log_tag, "io exception while communicating with zygote - "
                  ex.tostring());
        throw new zygotestartfailedex(ex);
    }
}

在介绍了zygote进程(孵化器进程)

3.1 zygote简介

  • zygote进程是一个用户进程,由init进程(1号进程)fork而来。
  • zygote进程通过fork的方式创建新的应用程序进程。
  • zygote进程的入口点是zygoteinit类中的main方法。

下面将简单介绍在zygote进程的代码流转。

3.2 zygoteinit.java

  • zygote进程是在android系统启动过程中创建的,创建完成后会通过zygoteserver来监听消息
public static void main(string argv[]) {
    zygoteserver zygoteserver = new zygoteserver();
    ...
    // 启动zygote,循环监听消息
    caller = zygoteserver.runselectloop(abilist);
    if (caller != null) {
        // 有新的消息就执行对应runnable代码
        caller.run();
    }
    ...
}

3.3 zygoteserver.java

  • zygoteserver获取到消息后会调用zygoteconnectionprocesscommand方法
runnable runselectloop(string abilist) {
    while (true) {
        // 使用 select 监听套接字
        structpollfd[] pollfds = new structpollfd[socketfds.size()];
        
        if (pollindex == 0) {
            // 接收到新的连接
            zygoteconnection newpeer = acceptcommandpeer(abilist);
            peers.add(newpeer);
            socketfds.add(newpeer.getfiledescriptor());
        } else {
            // 处理已有连接的请求
            zygoteconnection connection = peers.get(pollindex);
            final runnable command = connection.processcommand(this, multipleforksok);
        }
    }
}

3.4 zygoteconnection.java

  • zygoteconnectionprocesscommand方法最终调用zygoteinitzygoteinit方法

runnable processcommand(zygoteserver zygoteserver, boolean multipleok) {
    ...
    // 调用zygote的forkandspecialize方法fork出acitivity的进程
    pid = zygote.forkandspecialize(...);
    
    if (pid == 0) {
        // 在子进程中,即创建出来的应用程序所在进程
        return handlechildproc(parsedargs, childpipefd,
                parsedargs.mstartchildzygote);
    } else {
        // 在父线程中,pid为创建好的子进程的id
        handleparentproc(pid, serverpipefd);
        return null;
    }
}
private void handleparentproc(int pid, filedescriptor serverpipefd) {
    // 通过套接字socket将子进程的 pid 返回给请求方(activitymanagerservice)
    os.writeint(pid);
}
private runnable handlechildproc(...) {
    
        // 子进程负责应用程序后续的初始化工作
        zygoteinit.zygoteinit(...)
}
  • fork系统调用会创建一个新的进程(子进程)。在调用fork后,父进程和子进程(新创建出来的进程)会各自执行后续的代码。
  • 在父进程中,fork返回子进程的pid。这是一个正整数,表示新创建的子进程的进程id。
  • 在子进程中(新进程),fork 返回 0。这表示当前进程是新创建的子进程。
  • 应用程序(app)的进程就是新创建的子进程

3.5 再次回到zygoteinit.java

  • 调用runtimeinit.applicationinit方法,进行应用程序的初始化过程
public static runnable zygoteinit(...) {
    // 常见的初始化工作,例如设置系统属性、初始化默认的未捕获异常处理器等
    runtimeinit.commoninit();
    // zygote相关的初始化工作。这个初始化过程在c/c  层面进行,设置了必要的zygote运行环境
    zygoteinit.nativezygoteinit();
    // 调用runtimeinit.applicationinit方法,进行应用程序的初始化过程
    return runtimeinit.applicationinit(targetsdkversion, disabledcompatchanges, argv, classloader);
}

3.6 runtimeinit.java

  • runtimeinitapplicationinit方法完成初始化工作后,通过反射的方式,调用android.app.activitythreadmain方法
  • 参数列表中的startclass2.9 processlist.java源码中的entrypoint(android.app.activitythread)
protected static runnable applicationinit(...) {
    // 查找并返回应用程序的主方法
    return findstaticmain(args.startclass, args.startargs, classloader);
}
private static runnable findstaticmain(...) {
    // 反射得到android.app.activitythread类
    cl = class.forname(classname, true, classloader);
    // 反射获取main方法
    m = cl.getmethod("main", new class[] { string[].class });
    // 返回可被执行的runnable对象
	return new methodandargscaller(m, argv);
}

通过zygote进程fork出应用程序的进程后,下一步就是创建整个应用程序的application实例

4.1 activitythread.java

  • 创建应用程序的activitythread实例
  • 创建应用程序的application实例
  • 创建应用程序的looper循环
public static void main(string[] args) {
    // 初始化主线模块
    initializemainlinemodules();
    // 创建mainlooper
    looper.preparemainlooper();
    // 创建activitythread
    activitythread thread = new activitythread();
    // 创建应用程序application实例
    thread.attach(false, startseq);
    if (smainthreadhandler == null) {
        smainthreadhandler = thread.gethandler();
    }
    // 循环监听消息
    looper.loop();
}
@unsupportedappusage
private void attach(boolean system, long startseq) {
    // 获取activitymanagerservice实例
    final iactivitymanager mgr = activitymanager.getservice();
    // 调用activitymanagerservice的attachapplication方法
    mgr.attachapplication(mappthread, startseq);
}

4.2 activitymanagerservice.java

  • activitymanagerservice完成application创建和第一个activity的创建
@override
public final void attachapplication(iapplicationthread thread, long startseq) {
    // 调用attachapplicationlocked方法
    attachapplicationlocked(thread, callingpid, callinguid, startseq);
}
private void attachapplicationlocked(...) {
    // 调用activitythread的bindapplication方法创建并绑定application
    thread.bindapplication(...)
    // 在结束application创建后调用finishattachapplicationinner启动app的第一个activity页面,在4.5会介绍这一部分代码
    finishattachapplicationinner(startseq, callinguid, pid);
}

4.3 再次回到activitythread.java

  • 通过handler机制完成消息的传递,正式加载apk文件
public final void bindapplication(...) {
    appbinddata data = new appbinddata();
    ... // 构造data的数据
    // h为handler, bind_application是int值
    
    sendmessage(h.bind_application, data);
}
// activitythread的内部类h
class h extends handler {
    public void handlemessage(message msg) {
        switch (msg.what) {
            case bind_application:
                appbinddata data = (appbinddata)msg.obj;
                handlebindapplication(data);
                break;
        }
    }
}
@unsupportedappusage
private void handlebindapplication(appbinddata data) {
    application app;
    // 最终调用loadedapk的makeapplicationinner方法加载apk文件到内存中
    app = data.info.makeapplicationinner(data.restrictedbackupmode, null);
    // 调用application的oncreate方法,正式进入apk执行文件
    minstrumentation.callapplicationoncreate(app);
}

4.4 loadedapk.java

private application makeapplicationinner(...) {
    // 获取app的application类(在androidmanifast.xml中定义的),没有就使用默认的android.app.application
    string appclass = mapplicationinfo.getcustomapplicationclassnameforprocess(
            myprocessname);
    if (forcedefaultappclass || (appclass == null)) {
        appclass = "android.app.application";
    }
    // 调用instrumentation的newapplication方法创建application对象
    app = mactivitythread.minstrumentation.newapplication(
                    cl, appclass, appcontext);
}

4.5 instrumentation.java

  • instrumentation完成application实例的初始化,并调用oncreate方法
// 创建application对象
static public application newapplication(class clazz, context context) {
    // application实例的初始化
    application app = (application)clazz.newinstance();
    app.attach(context);
    return app;
}
// 调用application的oncreate方法
public void callapplicationoncreate(application app) {
    app.oncreate();
}

5.1 activitymanagerservice.java

  • 在执行完application的oncreate方法后,我们再回到activitymanagerservice.javaattachapplicationlocked方法中
  • attachapplicationlocked方法最终会调用localserviceattachapplication方法来加载我们的第一个acitivity页面
  • activitytaskmanagerinternal是定义在activitytaskmanagerservice.javalocalservice
private void attachapplicationlocked(...) {
    // 调用activitythread的bindapplication方法创建并绑定application
    thread.bindapplication(...)
    // 在结束application创建后调用finishattachapplicationinner启动app的第一个activity页面
    finishattachapplicationinner(startseq, callinguid, pid);
}
private void finishattachapplicationinner(long startseq, int uid, int pid) {
    if (normalmode) {
        try {
        // 调用`activitytaskmanagerinternal`(即activitytaskmanagerservice.localservice)的**attachapplication**方法来加载我们的第一个acitivity页面
            didsomething = matminternal.attachapplication(app.getwindowprocesscontroller());
        }
    }
}

5.2 activitytaskmanagerservice.java

  • 在localservice中调用rootwindowcontainer.attachapplication方法
final class localservice extends activitytaskmanagerinternal {
    @override
    public boolean attachapplication(windowprocesscontroller wpc){
        // 调用rootwindowcontainer的attachapplication
        return mrootwindowcontainer.attachapplication(wpc);
    }
}

5.3 rootwindowcontainer.java

  • 最终调用activitytasksupervisorrealstartactivitylocked方法
boolean attachapplication(windowprocesscontroller app) throws remoteexception {
    // 调用rootwindowcontainer内部类attachapplicationhelper的process方法
    return mattachapplicationhelper.process(app);
}
private class attachapplicationhelper implements consumer, predicate {
    boolean process(windowprocesscontroller app) throws remoteexception {
        mapp = app;
        for (int displayndx = getchildcount() - 1; displayndx >= 0; --displayndx) {
            // 通过/frameworks/base/services/core/java/com/android/server/wm/task.java中的forallroottasks调用test方法
            getchildat(displayndx).forallroottasks(this);
        }
    }
    
    public boolean test(activityrecord r) {
        // 调用activitytasksupervisor的realstartactivitylocked方法
        mtasksupervisor.realstartactivitylocked(...)
    }
}

5.3.1 task.java

boolean forallroottasks(predicate callback, boolean traversetoptobottom) {
    // 调用test方法
    return isroottask() ? callback.test(this) : false;
}

5.4 activitytasksupervisor.java

boolean realstartactivitylocked(activityrecord r, windowprocesscontroller proc,
            boolean andresume, boolean checkconfig) throws remoteexception {
        ...
        // 创建clienttransaction启动事务:
        final clienttransaction clienttransaction = clienttransaction.obtain(
                proc.getthread(), r.token);
        ...
        // 添加launchactivityitem回调
        clienttransaction.addcallback(launchactivityitem.obtain(new intent...));
        ...
        // 执行启动事务,调用clientlifecyclemanager的scheduletransaction方法
        mservice.getlifecyclemanager().scheduletransaction(clienttransaction);
        ...
}
  • clienttransaction事务对象,用于描述一系列客户端(即应用进程)需要执行的操作。
  • launchactivityitem回调参数中包括如何启动activity,启动所需的intent、配置、状态等信息。

5.4.1 clientlifecyclemanager.java

void scheduletransaction(clienttransaction transaction) throws remoteexception {
    final iapplicationthread client = transaction.getclient();
    // 调用clienttransaction的schedule
    transaction.schedule();
}

5.4.2 clienttransaction.java

public void schedule() throws remoteexception {
    // 调用mclient的scheduletransaction方法
    mclient.scheduletransaction(this);
}
  • mclientiapplicationthread接口,实际是activitythread的内部类applicationthread对象。
  • mclientactivitytasksupervisor的realstartactivitylocked方法中通过clienttransaction.obtain(proc.getthread(), r.token),具体可

5.5 回到activitythread.java

private class applicationthread extends iapplicationthread.stub {
    @override
    public void scheduletransaction(clienttransaction transaction) throws remoteexception {
        // 调用activitythread的scheduletransaction
        activitythread.this.scheduletransaction(transaction);
    }
}
  • scheduletransaction方法实际调用的是activitythread父类clienttransactionhandlerscheduletransaction方法

5.5.1 clienttransactionhandler.java

void scheduletransaction(clienttransaction transaction) {
   transaction.preexecute(this);
   // 将事务放入消息队列中,等待主线程的处理
   sendmessage(activitythread.h.execute_transaction, transaction);
}

5.5.2 activitythread的内部handler类h处理消息

public void handlemessage(message msg) {
    switch (msg.what) {
        case execute_transaction:
            final clienttransaction transaction = (clienttransaction) msg.obj;
            mtransactionexecutor.execute(transaction);
            break;
    }
}

5.5.3 transactionexecutor.java

public void execute(clienttransaction transaction) {
    // 执行事务中的回调和生命周期状态请求
    executecallbacks(transaction);
    executelifecyclestate(transaction);
}
public void executecallbacks(clienttransaction transaction) {
    final list callbacks = transaction.getcallbacks();
    // 遍历事务中的所有回调项,并调用每个回调项的execute方法。
    for (int i = 0, size = callbacks.size(); i < size;   i) {
        final clienttransactionitem item = callbacks.get(i);
        item.execute(mclient, mtransactionhandler, transaction.getlifecyclestaterequest());
    }
}
  • 每个回调项的execute方法实际就是调用launchactivityitemexecute方法

5.5.4 launchactivityitem.java

@override
public void execute(clienttransactionhandler client, ibinder token, pendingtransactionactions pendingactions) {
    client.handlelaunchactivity(new launchactivityitem.activityclientrecord(this), pendingactions, null);
}
  • 调用clienttransactionhandler即activitythreadhandlelaunchactivity方法

5.6 回到activitythread

public activity handlelaunchactivity(activityclientrecord r, pendingtransactionactions pendingactions, intent customintent) {
    // 调用performlaunchactivity
    final activity a = performlaunchactivity(r, customintent);
}
private activity performlaunchactivity(activityclientrecord r, intent customintent) {
    // 创建activity对象
    activity = minstrumentation.newactivity(cl, component.getclassname(), r.intent);
}

5.6.1 instrumentation.java

public activity newactivity(...) {
    // 创建activity
    activity activity = (activity)clazz.newinstance();
    ...
    return activity;
}

5.6.2 回到activitythread的performlaunchactivity方法

private activity performlaunchactivity(activityclientrecord r, intent customintent) {
    // 创建activity对象
    activity = minstrumentation.newactivity(cl, component.getclassname(), r.intent);
    // activity绑定上下文context
    activity.attach(appcontext, this, getinstrumentation(), r.token,...);
    // 调用instrumentation的callactivityoncreate方法
    minstrumentation.callactivityoncreate(activity, r.state, r.persistentstate);
}

5.6.3 instrumentation的callactivityoncreate方法

public void callactivityoncreate(activity activity, bundle icicle) {
    // 调用activity的performcreate方法
    activity.performcreate(icicle);
}

5.7 activity.java

  • 在activity中实现了生命周期方法的调用逻辑

5.7.1 oncreate方法

final void performcreate(...) {
    // 调用oncreate方法
    if (persistentstate != null) {
        oncreate(icicle, persistentstate);
    } else {
        oncreate(icicle);
    }
}
  • 绕了一大圈,最终又回到了activity.java
  • 在performcreate中调用oncreate生命周期方法

5.7.2 onstart方法

5.7.2.1 transactionexecutor.java

  • 在的方法execute中通过executecallbacks创建了activity并调用oncreate方法
  • 然后在executelifecyclestate方法中调用后续的生命周期方法
public void execute(clienttransaction transaction) {
    // 执行事务中的回调
    executecallbacks(transaction);
    // 执行生命周期
    executelifecyclestate(transaction);
}
public void executelifecyclestate(clienttransaction transaction) {
    final activitylifecycleitem lifecycleitem = transaction.getlifecyclestaterequest();
    if (lifecycleitem != null) {
        // 调用activitylifecycleitem的execute方法
        lifecycleitem.execute(transaction.getclienttransactionhandler(), token, pendingactions);
    }
}
  • activityresultitem是一个抽象类
  • 这里实际调用的是activityresultitemexecute方法

5.7.2.2 activityresultitem.java

public void execute(clienttransactionhandler client, ibinder token,
                    pendingtransactionactions pendingactions) {
    client.handleresumeactivity(token, true /* isforward */, "resume_activity");
}
  • 这里实际调用的是activitythreadhandleresumeactivity方法

5.7.2.3 activitythread的handleresumeactivity方法

public void handleresumeactivity(ibinder token, boolean finalstaterequest, string reason) {
    // 先调用activitythread的performstart方法
    performrestartactivity(r);
    // 再调用activity的performresume
    r.activity.performresume();
}
public void performrestartactivity(activityclientrecord r) {
    // 调用activity的performstart
    r.activity.performstart();
}

5.7.2.4 activity的performstart方法

final void performstart() {
    // 调用instrumentation的callactivityonstart方法
    minstrumentation.callactivityonstart(this);
}

5.7.2.5 instrumentation的callactivityonstart方法

public void callactivityonstart(activity activity) {
    activity.onstart();
}

5.7.3 onresume方法

5.7.2.3 activitythread的handleresumeactivity方法中提到在onstart方法执行后会调用r.activity.performresume();activity的performresume方法

5.7.3.1 activity的performresume方法

final void performresume(boolean followedbypause, string reason) {
    minstrumentation.callactivityonresume(this);
}

5.7.3.2 instrumentation的callactivityonresume方法

public void callactivityonresume(activity activity) {
    activity.onresume();
}
  • 至此activity创建完成,并完成了核心生命周期方法的创建
  • 在onresume方法后,activity进入前台,准备显示给用户

在生命周期完成后,应用程序就会被展示在屏幕上,后续的工作主要是渲染,这里做一个简单的流程说明

  • activity实例化时创建一个window对象,默认情况下是phonewindow。在phonewindow中,有一个 decorview,它是整个视图层次的根视图。
  • 在activity的oncreate方法中,activity会调用setcontentview方法,将布局资源加载到decorview中
  • windowmanager负责管理应用程序窗口,将decorview添加到窗口中
  • 当decorview被添加到窗口中后。viewrootimpl类负责视图层次结构的测量(measure)、布局(layout)和绘制(draw)
  • 最终由surfaceflinger合成并显示在屏幕上
返回顶部
顶部
网站地图