Activity启动startActivity

title: Activity启动startActivity


参考

startActivity(new Intent(this, SecondActivity.class));

其实在前台Activity中启动另一个Activity的过程主要分为以下几步:
原Activity的onPause
新Activity的onCreate
新Activity的onStart
新Activity的onResume
原Activity的onStop
原Activity的onSaveInstanceState

[/frameworks/base/core/java/android/app/Activity.java]

public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else { //执行else中的操作
            startActivityForResult(intent, -1); 
        }

[/framework/base/core/java/android/app/Instrumentation.java]

public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;      
        try {
        
            int result = ActivityManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);  //调用AMS.startActivity
            checkStartActivityResult(result, intent); //检查startActivity的结果
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
}

其中\color{red}{ ActivityManager.getService() }就是获取到AMS的句柄,然后调用==AMS.startActivity 。
[/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java]

@Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions,
                UserHandle.getCallingUserId());
    }

mActivityStarterController.obtainStarter函数返回一个ActivityStarter对象:

[/frameworks/base/services/core/java/com/android/server/am/ActivityStartController.java]

   /**
     * @return A starter to configure and execute starting an activity. It is valid until after
     *         {@link ActivityStarter#execute} is invoked. At that point, the starter should be
     *         considered invalid and no longer modified or used.
     */
    ActivityStarter obtainStarter(Intent intent, String reason) {
        return mFactory.obtain().setIntent(intent).setReason(reason);
    }

\color{red}{ ActivityStarter }类里面主要的执行的操作:

WMS.deferSurfaceLayout:暂停布局
ActivityStarter.startActivityUnchecked:关键函数,启动Activity
WMS.continueSurfaceLayout:继续布局
ActivityStarter.postStartActivityPorcessing

[/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java]


boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
 
        ......
 
        if (targetStack != null && isFocusedStack(targetStack)) { //执行该条件
            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
 
        ......
 
        return false;
    }
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
            ActivityRecord resuming, boolean pauseImmediately) {
        ...
        if (prev.app != null && prev.app.thread != null) {
            try {
                ...            mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
                        PauseActivityItem.obtain(prev.finishing, userLeaving,
                                prev.configChangeFlags, pauseImmediately));  //关键操作
            } catch (Exception e) {
                .....
            }
        } else {
            ...
        }   
        ...
    }

\color{red}{ mService.getLifecycleManager() 、 PauseActivityItem 是关键 (需要先暂停当前activity,在启动下一个activity) }

[//frameworks/base/services/core/java/com/android/server/am/ClientLifecycleManager.java ]

将PauseActivityItem对象设置到clientTransaction对象中。并返回该clientTransaction对象。

接下来看看ClientTransaction.schedule函数:

// /frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
    
    private IApplicationThread mClient;
 
    public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }

mClient实质就是应用进程与系统进程(system_server)通信的服务端,即ActivityThread.ApplicaitonThread对象。所以接下来调用到了ActivityThread.ApplicationThread.sheduleTransaction函数:

///frameworks/base/core/java/android/app/ActivityThread.java
        @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            ActivityThread.this.scheduleTransaction(transaction);
        }

\color{red}{ 会执行 (1) cycleToPath ; (2)PauseActivityitem.execute ; (3) ==PauseActivityItem.postExecute }。接着来分析一下这三个过程。

执行到TransactionExecutor.execute函数做了些什么:

// /frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
    /** Transition to the final state if requested by the transaction. */
    private void executeLifecycleState(ClientTransaction transaction) {
    
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); //根据前文描述,lifecycleItem就是PauseActivityItem对象
      
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
 
        // Execute the final transition with proper parameters.
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }

PauseActivityItem.postExecute
该函数涉及到了新的Activity的启动流程,后续再接着分析。先看一下该函数的code。

@Override
    public void postExecute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        if (mDontReport) {
            return;
        }
        try {
            // TODO(lifecycler): Use interface callback instead of AMS.
            ActivityManager.getService().activityPaused(token); //跨进程调用AMS.activityPaused函数
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }

接下来要启动的Activity所在进程已启动,所以执行的是realStartActivityLocked函数:

// /frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
     final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
 
        try { 
            try { 
                // Create activity launch transaction.
                final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                        r.appToken);
                clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),...,
                        profilerInfo));  //【1】将LaunchActivityItem这个callback添加到clientTransaction
 
                // Set desired final state.
                final ActivityLifecycleItem lifecycleItem;
                if (andResume) { //andResume值为true
                    lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward()); 
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                clientTransaction.setLifecycleStateRequest(lifecycleItem); //【2】将ResumeActivityItem设置给clientTransaction
 
 
                // Schedule transaction.
                mService.getLifecycleManager().scheduleTransaction(clientTransaction); //【3】调用ClientLifecycleManager.scheduleTransaction分发事务
 
                ...
 
            } catch (RemoteException e) {
                throw e;
            }
        }
          
        return true;
    }

该函数主要的操作:

\color{red}{ allPausedActivitiesComplete:原Activity是否pause完成}
\color{red}{ clientTransaction.addCallback: 将LaunchActivityItem这个callback添加到clientTransaction }
\color{red}{clientTransaction.setLifecycleStateRequest: 将ResumeActivityItem设置给clientTransaction}

\color{red}{ mService.getLifecycleManager().scheduleTransaction:调度分发事务 }

// /frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
    
    public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }

此处的mClient是与系统进程通信的服务端,即ActivityThread.ApplicationThread,即此处调用的是ActivityThread.ApplicationThread.scheduleTransaction:

@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
     ActivityThread.this.scheduleTransaction(transaction);
}
 
    public void execute(ClientTransaction transaction) {
        final IBinder token = transaction.getActivityToken();
        log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
 
        executeCallbacks(transaction);
 
        executeLifecycleState(transaction);
        mPendingActions.clear();
        log("End resolving transaction");
    }

此函数中依然有2个操作:

\color{red}{ executeCallbacks 如前文realStartActivityLocked函数所述,LaunchActivityItem被加入到了callback }中。所以此处的:

// /frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java
/** Cycle through all states requested by callbacks and execute them at proper times. */
    @VisibleForTesting
    public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
       
        final int size = callbacks.size(); //callbacks.size = 1
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i); //item即是LaunchActivityItem
     
            if (closestPreExecutionState != UNDEFINED) {
                cycleToPath(r, closestPreExecutionState);
            }

            item.execute(mTransactionHandler, token, mPendingActions); //【1】
            item.postExecute(mTransactionHandler, token, mPendingActions); 
          
        }
    }
// /frameworks/base/core/java/android/app/ActivityThread.java    
    /**
     * Extended implementation of activity launch. Used when server requests a launch or relaunch.
     */
    @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
 
        // Make sure we are running with the most recent config.
        handleConfigurationChanged(null, null); //确保使用了最新的配置信息
 
        final Activity a = performLaunchActivity(r, customIntent); //【关键操作】
 
        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
           
        } else {  //如果launch activity失败,则finish Activity
            // If there was an error, for any reason, tell the activity manager to stop us.
           
        }
 
        return a;
    }

\color{red}{ LaunchActivityItem.execute }里面
函数里做了主要做了两件事:
①handleConfigurationChanged:确保启动的Activity使用的是最新的配置
②performLaunchActivity:启动Activity

// /frameworks/base/core/java/android/app/ActivityThread.java
    /**  Core implementation of activity launch. */
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        //从ActivityClientRecord中获取待启动Activity的信息
        ActivityInfo aInfo = r.activityInfo;
       
        ComponentName component = r.intent.getComponent();  //【1】获取ComponentName
       
        ContextImpl appContext = createBaseContextForActivity(r); //【2】创建Context
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent); //【3】使用类加载器新建Activity
           
        } catch (Exception e) {
          
        }

        try {
            //【4】创建Application,也是通过类加载器来创建的,
            //创建完毕后会通过调用Instrumentation.callApplicationOnCreate来调用Application的onCreate方法e
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
 
            
            if (activity != null) {
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);  
                if (r.overrideConfig != null) {
                    config.updateFrom(r.overrideConfig); //应用配置信息
                }
                appContext.setOuterContext(activity); //【5】将新的Activity与新建的context关联
                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);//attach方法中Activity会完成Window的创建并建立自己与Window的关联,这样当Window接收到外部输入事件后就可以将事件传递给Activity
 
            }
            r.setState(ON_CREATE); //记录当前Activity的状态为ON_CREATE
 
            mActivities.put(r.token, r);
              mInstrumentation.callActivityOnCreate(activity, r.state);  //【6】调用Instrumentation.callActivityOnCreate执行onCreate流程

 
        } catch (SuperNotCalledException e) {
        } catch (Exception e) {
           
        }

        return activity;
    }

\color{red}{ launch activity的核心实现 },主要完成的工作:

ComponentName component:获取ComponentName
ContextImpl appContext:创建Context
Activity activity:新建Activity
Application app:创建Application
activity.attach:管理activity与context
callActivityOnCreate:启动Activity
其实这个函数非常重要,但是我们此时关注的是Activity的生命周期流程,所以还是直接看Instrumentation.callActivityOnCreate函数

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

    public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }

,此函数中有三个操作:

①prePerformCreate:create操作之前做的事

②activity.performCreate:create操作

③postPerformCreate:create操作之后做的事

// /frameworks/base/core/java/android/app/Activity.java
    final void performCreate(Bundle icicle) {
        performCreate(icicle, null);
    }
    
    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        mCanEnterPictureInPicture = true;
        restoreHasCurrentPermissionRequest(icicle);
        if (persistentState != null) { //传入的参数persistentState =null
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle); //调用了onCreate函数
        }
        writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
        mActivityTransitionState.readState(icicle);
 
        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
                com.android.internal.R.styleable.Window_windowNoDisplay, false);
        mFragments.dispatchActivityCreated(); //fragment的create处理
        mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
    }

executeLifecycleState
先看源码:

// /frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
  
    private void executeLifecycleState(ClientTransaction transaction) {
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        if (lifecycleItem == null) {
            // No lifecycle request, return early.
            return;
        }
   
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
 
        // Execute the final transition with proper parameters.
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }

如前文所述,此处的ActivityLifecycleItem参数为ResumeActivityItem,所以该函数实际完成的操作:

(1) ResumeActivityItem.execute

(2)ResumeActivity.postExecute

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,311评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,339评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,671评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,252评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,253评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,031评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,340评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,973评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,466评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,937评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,039评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,701评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,254评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,259评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,485评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,497评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,786评论 2 345

推荐阅读更多精彩内容