慢~再来梳理一遍Activity的启动流程

前言

activity启动的流程分为两部分:一是在activity中通过startActivity(Intent intent)方法启动一个Activity;二是我们在桌面通过点击应用图标启动一个App然后显示Activity;第二种方式相较于第一种方式更加全面,所以本文会以第二种流程来分析。

简要

我们手机的桌面是一个叫做Launcher的Activity,它罗列了手机中的应用图标,图标中包含安装apk时解析的应用默认启动页等信息。在点击应用图标时,即将要启动的App和Launcher、AMS、Zygote所属进程不同所以涉及到Launcher与AMS,AMS与Zygote,AMS与新App这四者多次通信,才会启动一个App,然后再启动Activity,整体的时序图如下:

一.Launcher向AMS发送启动Activity

在用户点击应用图标时,Launcher这个Activity会调用startActivitySafely方法,最后调用到Activity.startActivity方法,方法调用流程如下:

Launcher.java
   public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
       ...
       //标记在新的栈启动
       intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       ...
       startActivity(intent, optsBundle);
       ...
   }

Activity.java


   @Override
   public void startActivity(Intent intent, @Nullable Bundle options) {
       ...
       if (options != null) {
           //-1为requestCode表明不需要知道是否启动成功
           startActivityForResult(intent, -1, options);
       } else {
           startActivityForResult(intent, -1);
       }
   }

   public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
           @Nullable Bundle options) {
           ...
           Instrumentation.ActivityResult ar =
               mInstrumentation.execStartActivity(
                   this, mMainThread.getApplicationThread(), mToken,this,intent, requestCode, options);
           ...
    }

每个Activity都持有Instrumentation对象,通过它的execStartActivity方法来继续完成启动Activity的流程,要注意的是这个方法中传入了mMainThread.getApplicationThread(),它获取到的是ActivityThread的内部类ApplicationThread实例,这是一个Binder对象,之后AMS通过此对象与App通信。

Instrumentation.java
public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
    ...
	int result = ActivityTaskManager.getService().startActivity(whoThread,who.getBasePackageName(),
        who.getAttributionTag(),intent,intent.resolveTypeIfNeeded(who.getContentResolver()),
        token,target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); 
    ...
}

ActivityTaskManager.java
public static IActivityTaskManager getService() {
       return IActivityTaskManagerSingleton.get();
}
    
private static final Singleton IActivityTaskManagerSingleton =
            new Singleton() {
                @Override
                protected IActivityTaskManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                    return IActivityTaskManager.Stub.asInterface(b);
                }
             }
};

这一步Launcher开始向AMS通信,由于在不同的进程所以需要通过Binder来通信,IActivityTaskManager是一个代理AMS端Binder的对象,之后AMS开始startActivity。

到这里Launcher向AMS请求启动一个Activity的流程就结束了。

二.AMS启动Activity并通知Launcher进入Paused状态

接下来的流程我们切换到AMS所在的进程继续分析,上一步通过代理调用到AMS的startActivity方法,接下来的调用如下:

ActivityTaskManagerService.java
    @Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
            String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
            Bundle bOptions) {
        return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
                resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
                UserHandle.getCallingUserId());
    }
    
    @Override
    public int startActivityAsUser(IApplicationThread caller, String callingPackage,
            String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
            String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
            Bundle bOptions, int userId) {
        return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
                resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
                true /*validateIncomingUser*/);
    }
    
    private int startActivityAsUser(IApplicationThread caller, String callingPackage,
            @Nullable String callingFeatureId, Intent intent, String resolvedType,
            IBinder resultTo, String resultWho, int requestCode, int startFlags,
            ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
	    ...
        userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
                Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
                
        return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setCallingFeatureId(callingFeatureId)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setUserId(userId)
                .execute();
    }
    
    ActivityStarter obtainStarter(Intent intent, String reason) {
        return mFactory.obtain().setIntent(intent).setReason(reason);
    }

上面几步主要是做权限检查

ActivityStarter.java
 int execute() {
 ...
 res = executeRequest(mRequest);
 ...
 }
//层层调用会到下面这个方法
ActivityStack.java
 private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    ...
    if (mResumedActivity != null) {
       pausing |= startPausingLocked(userLeaving, false , next);
    }
    ...
    mStackSupervisor.startSpecificActivity(next, true, false);
    ...
 }

startPausingLocked方法主要是通知Launcher进入Paused状态,在它进入这个状态后,再通过ActivityStackSupervisor.startSpecificActivity方法判断要启动的Activity所属进程的状态做出不同响应。

ActivityStackSupervisor.java
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
        // 获取要启动的Activity进程信息
        final WindowProcessController wpc =
                mService.getProcessController(r.processName, r.info.applicationInfo.uid);
        boolean knownToBeDead = false;
        //如果进程存在且有进程中有线程存在 就是启动一个同应用的Activity(普通Activity就在此执行)
        if (wpc != null && wpc.hasThread()) {
            try {
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }

            // If a dead object exception was thrown -- fall through to
            // restart the application.
            knownToBeDead = true;
        }
	//否则通过AMS向Zygote进程请求创建新的进程
        r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
        final boolean isTop = andResume && r.isTopRunningActivity();
        mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
}

截止到这里完成了Launcher和AMS的通信,以及AMS和Zygote进程的通信,接下来我们要创建要启动的App的线程,即ActivityThread。

三.新的进程启动,ActivityThread的main函数入口

上一部分的最后Zygote启动新的进程时会标记ActivityThread.main函数,在Zygote创建好新进程后通过反射调用此方法,之后的流程处于新的App进程中,当然还是会与AMS进行一些通信的。

ActivityThread.java
    public static void main(String[] args) {
        ...
        Looper.prepareMainLooper();
	...
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);
	...
        Looper.loop();
	...
    }
    
    private void attach(boolean system, long startSeq) {
            final IActivityManager mgr = ActivityManager.getService();
            try {
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
            ...
    }
ActivityManagerService.java
    private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
            int pid, int callingUid, long startSeq) {
            ...
            thread.bindApplication(processName, appInfo, providerList,
                        instr2.mClass,
                        profilerInfo, instr2.mArguments,
                        instr2.mWatcher,
                        instr2.mUiAutomationConnection, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.isPersistent(),
                        new Configuration(app.getWindowProcessController().getConfiguration()),
                        app.compat, getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, autofillOptions, contentCaptureOptions,
                        app.mDisabledCompatChanges);
             ...
             didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
             ...
    }

这里主要是创建了Looper和ActivityThread对象,然后将当前应用ApplicationThread注册到AMS中,ApplicationThread是ActivityThread的内部类实现了IApplicationThread.Stub用此对象可跨进程通信。

上面的代码逻辑分两步:

第一步,在AMS绑定ApplicationThread时,发送了一个H.BIND_APPLICATION的Message,在Handler中处理该消息时调用了Application的onCreate方法。

第二步,在mAtmInternal的attachApplication层层调用到ActivityStackSupervisor.realStartActivityLocked方法,进入准备Activity事务阶段。

整体如下:

public final void bindApplication(String processName, ApplicationInfo appInfo,
                ProviderInfoList providerList, ComponentName instrumentationName,
                ProfilerInfo profilerInfo, Bundle instrumentationArgs,
                IInstrumentationWatcher instrumentationWatcher,
                IUiAutomationConnection instrumentationUiConnection, int debugMode,
                boolean enableBinderTracking, boolean trackAllocation,
                boolean isRestrictedBackupMode, boolean persistent, Configuration config,
                CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
                String buildSerial, AutofillOptions autofillOptions,
                ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges) {
                	...
                	sendMessage(H.BIND_APPLICATION, data);
 }
                
public void handleMessage(Message msg) {
    switch (msg.what) {
       case BIND_APPLICATION:
       	AppBindData data = (AppBindData)msg.obj;
       	handleBindApplication(data);
       	Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
       	break;
        ...
      }
}

private void handleBindApplication(AppBindData data) {
	...
	mInstrumentation.callApplicationOnCreate(app);
	...
}

到这里为止,新的App线程已经启动并且绑定了Application。

四.创建Activity

ActivityStackSupervisor.java
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
       boolean andResume, boolean checkConfig) throws RemoteException {
       ...
       final ClientTransaction clientTransaction = ClientTransaction.obtain(
                proc.getThread(), r.appToken);
         final DisplayContent dc = r.getDisplay().mDisplayContent;
         //这里生命周期添加的是LaunchActivityItem
         clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                 System.identityHashCode(r), r.info,
                 mergedConfiguration.getGlobalConfiguration(),
                 mergedConfiguration.getOverrideConfiguration(), r.compat,
                 r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
                 r.getSavedState(), r.getPersistentSavedState(), results, newIntents,
                 dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                 r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));

         final ActivityLifecycleItem lifecycleItem;
         if (andResume) {
             //这里添加了ResumeActivityItem
             lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
         } else {
             lifecycleItem = PauseActivityItem.obtain();
         }
         clientTransaction.setLifecycleStateRequest(lifecycleItem);
         //执行clientTransaction
         mService.getLifecycleManager().scheduleTransaction(clientTransaction);
         ...
}

ClientTransaction管理了Activity的启动信息,LaunchActivityItem继承ActivityLifecycleItem,具象化了Activity的生命周期,并可ClientLifecycleManager由执行,接下来scheduleTransaction方法中发送了EXECUTE_TRANSACTION的消息给ActivityThread的H类处理,然后再执行TransactionExecutor.execute(),最后执行handleLaunchActivity方法,如下

    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();
        ...
    }

    public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }

    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

    class H extends Handler {
         ...
         public void handleMessage(Message msg) {
         ...
            case EXECUTE_TRANSACTION:
                final ClientTransaction transaction = (ClientTransaction) msg.obj;
                mTransactionExecutor.execute(transaction);
                if (isSystem()) {
                    transaction.recycle();
                }
                break;
         ...
         }  
         ...
    }

    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        ...
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
    }

接下来由ActivityThread来处理后续操作

public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        ...
        final Activity a = performLaunchActivity(r, customIntent);
        ...
        return a;
}

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ContextImpl appContext = createBaseContextForActivity(r);
        ...
        //反射创建Activity
        java.lang.ClassLoader cl = appContext.getClassLoader();
        activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
        ...
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);
        ...
        activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback,
                        r.assistToken);
        ...
        activity.setTheme(theme);
        ...
        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
}

performLaunchActivity方法中主要做了以下几件事:

  1. 创建要启动activity的上下文环境
  2. 通过Instrumentation的newActivity方法,以反射形式创建activity实例
  3. 如果Application不存在的话会创建Application并调用Application的onCreate方法
  4. 初始化Activity,创建Window对象(PhoneWindow)并实现Activity和Window相关联
  5. 通过Instrumentation调用Activity的onCreate方法

总结

根Activity启动流程整体上学习意义较大,建议从整体流程入手,然后可以对细节推敲,遇到流程不通时也可以debug。 Activity的整体启动流程:

  1. 点击图标,Launcher向AMS请求启动该App
  2. AMS反馈收到启动请求,并告知Launcher进入pause状态
  3. Launcher进入Paused状态并告知AMS
  4. AMS检测新的App是否已启动,否则通知Zygote创建新的进程并调用ActivityThread.main方法
  5. 应用进程启动ActivityThread
  6. ActivityThread中H类处理需要启动Activity的请求消息

最后

如果本文提供了有效信息还烦请点个小赞,如果有什么出入可以评论或私信我,感谢。

文章来源于互联网:慢~再来梳理一遍Activity的启动流程

阅读全文
下载说明:
1、本站所有资源均从互联网上收集整理而来,仅供学习交流之用,因此不包含技术服务请大家谅解!
2、本站不提供任何实质性的付费和支付资源,所有需要积分下载的资源均为网站运营赞助费用或者线下劳务费用!
3、本站所有资源仅用于学习及研究使用,您必须在下载后的24小时内删除所下载资源,切勿用于商业用途,否则由此引发的法律纠纷及连带责任本站和发布者概不承担!
4、本站站内提供的所有可下载资源,本站保证未做任何负面改动(不包含修复bug和完善功能等正面优化或二次开发),但本站不保证资源的准确性、安全性和完整性,用户下载后自行斟酌,我们以交流学习为目的,并不是所有的源码都100%无错或无bug!如有链接无法下载、失效或广告,请联系客服处理!
5、本站资源除标明原创外均来自网络整理,版权归原作者或本站特约原创作者所有,如侵犯到您的合法权益,请立即告知本站,本站将及时予与删除并致以最深的歉意!
6、如果您也有好的资源或教程,您可以投稿发布,成功分享后有站币奖励和额外收入!
7、如果您喜欢该资源,请支持官方正版资源,以得到更好的正版服务!
8、请您认真阅读上述内容,注册本站用户或下载本站资源即您同意上述内容!
原文链接:https://www.dandroid.cn/archives/21174,转载请注明出处。
0

评论0

显示验证码
没有账号?注册  忘记密码?