Android程序是如何启动?Activity生命周期如何调用?

疑问: 1.Android程序是如何启动,Activity生命周期如何调用?我也想知道,参考很多博客,当然鄙人实在是才疏学浅,通过系统源码跟着博客一步一步的查看程序启动流程。以下是记录查看Android SDK 27版本源码流程。

1、找到ActivityThread类的main()方法
//创建ActivityThread,并且依附于Application的Thread
 ActivityThread thread = new ActivityThread();
 thread.attach(false);

-->进入attach(false)方法

//这里是Bind接口,说明APP与系统是通过Bind跨进程通信的
RuntimeInit.setApplicationObject(mAppThread.asBinder());
final IActivityManager mgr = ActivityManager.getService();
try {
      //这里是将Bind接口与应用的线程进行关联
      mgr.attachApplication(mAppThread);
    } catch (RemoteException ex) {
      throw ex.rethrowFromSystemServer();
 }
2、找到ApplicationThread,看这个线程主要做了什么事?

在这里面你会发现很多和生命周期相关方法,那么我们找到scheduleLaunchActivity()方法,这个方法由系统服务调用。

            updateProcessState(procState, false);
            ActivityClientRecord r = new ActivityClientRecord();
            r.token = token;
            r.ident = ident;
            r.intent = intent;
            r.referrer = referrer;
            r.voiceInteractor = voiceInteractor;
            r.activityInfo = info;
            r.compatInfo = compatInfo;
            r.state = state;
            r.persistentState = persistentState;
            r.pendingResults = pendingResults;
            r.pendingIntents = pendingNewIntents;
            r.startsNotResumed = notResumed;
            r.isForward = isForward;
            r.profilerInfo = profilerInfo;
            r.overrideConfig = overrideConfig;
            updatePendingConfiguration(curConfig);
            //关键来了:这里是通过Handler消息机制改变Activity状态了
            sendMessage(H.LAUNCH_ACTIVITY, r);
3、找到H类,对应找到H.LAUNCH_ACTIVITY事件处理逻辑代码
case LAUNCH_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                }
 break;

上述代码对应handleLaunchActivity(r, null, "LAUNCH_ACTIVITY")处理启动Activity

进入到handleLaunchActivity(r, null, "LAUNCH_ACTIVITY")方法里面,会发现这么一句代码Activity a = performLaunchActivity(r, customIntent)执行启动Activity。

进入performLaunchActivity(r, customIntent) 方法里面:通过反射创建一个Activity

Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            if (r.state != null) {
                r.state.setClassLoader(cl);
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to instantiate activity " + component
                    + ": " + e.toString(), e);
            }
        }

接着你会发现这么一段代码:callActivityOnCreate(activity, r.state, r.persistentState);实际上层层调用到Activity的onCreate() 方法

if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }

performLaunchActivity()执行完成之后,返回一个Activity的实例。这里Activity的onCreate()方法执行完毕。

接着根据performLaunchActivity()返回的Activity实例,执行 handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);

        Activity a = performLaunchActivity(r, customIntent);
        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            reportSizeConfigurations(r);
            Bundle oldState = r.state;
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);

            if (!r.activity.mFinished && r.startsNotResumed) {
                // The activity manager actually wants this one to start out paused, because it
                // needs to be visible but isn't in the foreground. We accomplish this by going
                // through the normal startup (because activities expect to go through onResume()
                // the first time they run, before their window is displayed), and then pausing it.
                // However, in this case we do -not- need to do the full pause cycle (of freezing
                // and such) because the activity manager assumes it can just retain the current
                // state it has.
                performPauseActivityIfNeeded(r, reason);

                // We need to keep around the original state, in case we need to be created again.
                // But we only do this for pre-Honeycomb apps, which always save their state when
                // pausing, so we can not have them save their state when restarting from a paused
                // state. For HC and later, we want to (and can) let the state be saved as the
                // normal part of stopping the activity.
                if (r.isPreHoneycomb()) {
                    r.state = oldState;
                }
            }
        } else {
            // If there was an error, for any reason, tell the activity manager to stop us.
            try {
                ActivityManager.getService()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                            Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        }

进入到handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
里面

r = performResumeActivity(token, clearHide, reason);

再进入到performResumeActivity(token, clearHide, reason);里面你会发现这么一句代码

r.activity.performResume();

进入到performResume()里面,你会发现

// mResumed is set by the instrumentation
mInstrumentation.callActivityOnResume(this);

上述代码经过层层调用,最终调用到activity.onResume();这里就开始执行Activity的onResume()方法。从APP程序启动到Activity的生命周期函数调用顺序流程就一幕了然了。

你可能感兴趣的:(Android程序是如何启动?Activity生命周期如何调用?)