当前位置:   article > 正文

Android启动(八)Activity启动_android startactivity

android startactivity

Activity的启动流程

Activity的启动流程分两种

  • 一是从桌面点击图标,启动MainActivity
  • 二是从程序内调用StartActivity 启动Activity
    • 二者区别就在于
      • 第一种要启动进程在启动MainActivity
      • 第二种是直接启动Activity

这里说下第二种 区别于第一种 就是省略了一个启动应用进程的步骤

## 步骤总结

  1. 调用StartActivity获取AMS的Binder代理对象,该对象利用Binder驱动通知AMS要启动一个Activity的消息.

  2. (AMS管理启动Activity)AMS接收到消息之后,开始管理启动MainActivity的工作,并通过Binder驱动通知给Launcher自己要创建Activity,需要launcer进入Paused状态,当Launcher进入paused状态之后,就开始启动Activity

  3. 启动Activity,判断当前的Activity所属的应用进程是否存在

    若存在,则执行realStartActivityLocked方法去启动准备好的Activity

  4. AMS利用binder通知ActivityThread来启动Activity

    1. 通过Handler发送Launcher_activity来启动Activity
      1. 先通过classsLoader加载activity
      2. 通过mInstrumentation执行Activity的onCreate
        1. mInstrumentation它用来监控应用程序和系统的交互。

代码分析

1.1获取AMS代理通知AMS要启动Activity

调用StartActivity,最终会执行到startActivityForResult

startActivityForResult

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
    ····
    Instrumentation.ActivityResult ar =
        mInstrumentation.execStartActivity(
            this, mMainThread.getApplicationThread(), mToken, this,
            intent, requestCode, options);
	···
   }
 }
public ActivityResult execStartActivity(
           Context who, IBinder contextThread, IBinder token, Activity target,
           Intent intent, int requestCode, Bundle options) {
       IApplicationThread whoThread = (IApplicationThread) contextThread;
       ................
  		 int result = ActivityManager.getService()
             .startActivity(whoThread, who.getBasePackageName(), intent,
                     intent.resolveTypeIfNeeded(who.getContentResolver()),
                     token, target != null ? target.mEmbeddedID : null,
                     requestCode, 0, null, options);
      ..................           
     return null;
 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 通过mInstrumentation.execStartActivity来启动Activity
    • mInstrumentation是Activity类的成员变量,它的类型是Intrumentation,它用来监控应用程序和系统的交互。
    • mMainThreadmMainThread也是Activity类的成员变量,它的类型是ActivityThread,它代表的是应用程序的主线程
      • 这里通过mMainThread.getApplicationThread()来获取它里面的ApplicationThread成员变量,它是一个Binder对象,后面ActivityManagerService会使用它来和ActivityThread来进行进程间通信。
      • 这里我们需注意的是,这里的mMainThread代表的是Launcher应用程序运行的进程
    • mToken也是Activity类的成员变量,它是一个Binder对象的远程接口,也就是Launcher这个Activity里的一个Binder对象 也就是下文中的resultTo
1.2.1 获取AMS代理对象

通过ActivityManager.getService()获取AMS的代理对象

public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }
	//利用单例获取,通过Binder驱动获取amd的dialing对象
    private static final Singleton<IActivityManager> IActivityManagerSingleton =
            new Singleton<IActivityManager>() {
                @Override
                protected IActivityManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
                    return am;
                }
            };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • ActivityManager.getService()返回ActivityManagerService的代理对象
    • ActivityManagerService 实现了IActivityManager接口
  • 调用代理对象的.startActivity方法通过Binder驱动就会执行Ams的StartActivity
1.2.2 通知AMS启动Activity

execStartActivity方法中,AMs的代理对象调用了start方法,通过Binder驱动就会执行AMS中的StartActivity

ActivityManager.getService().startActivity-》AMS.StartActivity()

AMS源码位置

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());
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 此时AMS已经接收到了消息,开始进入第二步了,AMS管理启动Activity

2.1 AMS管理启动Activity

AMS源码位置

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
            						Intent intent, String resolvedType, IBinder resultTo,
                                    String resultWho,int requestCode,int startFlags, 	                                     ProfilerInfo profilerInfo, Bundle bOptions, 
                                    int userId) {
        return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                profilerInfo, null, null, bOptions, false, userId, null, null,
                "startActivityAsUser");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 简单的参数传递执行到了ActivityStarter#startActivityMayWait
    • ActivityStarter源码位置
    • frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
  • ActivityStarter#startActivityMayWait
final int startActivityMayWait(IApplicationThread caller, int callingUid,
                               String callingPackage, Intent intent,
                               String resolvedType,IVoiceInteractionSession voiceSession,                                IVoiceInteractor voiceInteractor,IBinder resultTo,
                               String resultWho, int requestCode, int startFlags,
                               ProfilerInfo profilerInfo, WaitResult                                                    outResult,Configuration globalConfig, Bundle bOptions,
                               boolean ignoreTargetSecurity, int userId,
                               IActivityContainer iContainer,
                               TaskRecord inTask, String reason) {
	    ..................
        boolean componentSpecified = intent.getComponent() != null;
		..................
        intent = new Intent(intent);
		......................省略intent赋值部分
        ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId);
        .....................
        // 1 根据intent去收集需要启动的activity的信息,包名和要启动的MainActivity
        ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
		
        ActivityOptions options = ActivityOptions.fromBundle(bOptions);
        ActivityStackSupervisor.ActivityContainer container =
				(ActivityStackSupervisor.ActivityContainer)iContainer;
     ..................
      synchronized (mService) {
          final ActivityStack stack;
            if (container == null || container.mStack.isOnHomeDisplay()) {
                stack = mSupervisor.mFocusedStack;
            } else {
                stack = container.mStack;
            }
         ................................
            final ActivityRecord[] outRecord = new ActivityRecord[1];
         	// 2
            int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
                    aInfo, rInfo, voiceSession, voiceInteractor,
                    resultTo, resultWho, requestCode, callingPid,
                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,options, ignoreTargetSecurity, componentSpecified, outRecord, container,
                    inTask, reason);
            return res;
        }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 在注释1 位置,获取Activity相关的信息,保存在ActivityInfo中
  • 注释2 调用startActivityLocked进一步操作
  • 注释3 通知通知launcher要启动Activity请进入paused

2.2 调用startActivityLocked进一步操作

ActivityStarter#startActivityLocked

int startActivityLocked(IApplicationThread caller, Intent intent, 
                         Intent ephemeralIntent,String resolvedType,
                         ActivityInfo aInfo, ResolveInfo rInfo,
                         IVoiceInteractionSession voiceSession,
                         IVoiceInteractor voiceInteractor,IBinder resultTo, 
                         String resultWho, int requestCode, int callingPid, 
                         int callingUid,String callingPackage, int realCallingPid, 
                         int realCallingUid, int startFlags,ActivityOptions options,                              boolean ignoreTargetSecurity, boolean componentSpecified,
                         ActivityRecord[] outActivity, 				                                              ActivityStackSupervisor.ActivityContainer container,
                         TaskRecord inTask, String reason) {
     .................
     mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, 														  resolvedType, aInfo, rInfo, voiceSession,
                                              voiceInteractor, resultTo, resultWho, 												  requestCode,  callingPid, callingUid, 
                                              callingPackage, realCallingPid,                                                           realCallingUid, startFlags,options,
                                              ignoreTargetSecurity, componentSpecified,                                              mLastStartActivityRecord,container, inTask);
    ...................
     return mLastStartActivityResult;
 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 参数传递,执行一个startActivity
2.2.1 创建ActivityRecord
private int startActivity(IApplicationThread caller, Intent intent, 
                          Intent ephemeralIntent,String resolvedType, ActivityInfo aInfo,                           ResolveInfo rInfo,IVoiceInteractionSession voiceSession, 
                          IVoiceInteractor voiceInteractor,IBinder resultTo, 
                          String resultWho, int requestCode, int callingPid,
                          int callingUid,String callingPackage, int realCallingPid,
                          int realCallingUid, int startFlags,ActivityOptions options,
                          boolean ignoreTargetSecurity, boolean componentSpecified,
                          ActivityRecord[] outActivity, 
                          ActivityStackSupervisor.ActivityContainer container,
                          TaskRecord inTask) {
        int err = ActivityManager.START_SUCCESS;
        // Pull the optional Ephemeral Installer-only bundle out of the options early.
        final Bundle verificationBundle
                = options != null ? options.popAppVerificationBundle() : null;
		   //从传进来的参数caller得到调用者的进程信息,并保存在callerApp变量中,
    	  //这里就是Launcher应用程序的进程信息了。
        ProcessRecord callerApp = null;
        if (caller != null) {
            callerApp = mService.getRecordForAppLocked(caller);
            if (callerApp != null) {
                callingPid = callerApp.pid;
                callingUid = callerApp.info.uid;
            } else {
               ................
            }
        }
		   ................................
		   //保存launcher的binder对象
    	   //参数resultTo是Launcher这个Activity里面的一个Binder对象
    	   //通过它可以获得Launcher这个Activity的相关信息,保存在sourceRecord变量中。
        ActivityRecord sourceRecord = null;
        ActivityRecord resultRecord = null;
        if (resultTo != null) {
            sourceRecord = mSupervisor.isInAnyStackLocked(resultTo);
            if (DEBUG_RESULTS) Slog.v(TAG_RESULTS,
                    "Will send result to " + resultTo + " " + sourceRecord);
            if (sourceRecord != null) {
                if (requestCode >=  && !sourceRecord.finishing) {
                    resultRecord = sourceRecord;
                }
            }
        }
		   .............
    	   //创建即将要启动的Activity的相关信息,并保存在r变量中	
        ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, 	                                        callingUid,callingPackage, intent, resolvedType, aInfo,                                  mService.getGlobalConfiguration(),resultRecord, resultWho,
                               requestCode, componentSpecified, voiceSession != null,
                               mSupervisor, container, options, sourceRecord);
		
        return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true, options, inTask, outActivity);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 保存launcher的Binder对象
  • 创建ActivityRecord 把要启动的Activity信息封装到里面
  • 又执行了一个startActivity
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
        int result = START_CANCELED;
      try {
            mService.mWindowManager.deferSurfaceLayout();
            result = startActivityUnchecked(r, sourceRecord, voiceSession, 		                                                     voiceInteractor,startFlags, doResume, 
                                            options, inTask, outActivity);
        } finally {
          ............
        }
			..................
        return result;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 参数传递执行startActivityUnchecked
2.2.2 给创建的Activityrecord找到它的TaskRecord和ActivityStack

ActivityStarter#startActivityUnchecked

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {

        // 初始化ActivityStarter全局变量
			setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, 	                           voiceSession,voiceInteractor);
			// 检测Activity是否启动模式,是否需要在新的栈中启动,对与新的进程、SingleTask、SingleInstance启动模式就需要在新的栈中启动, 一般是判断是否需要在mLaunchFlags中加入FLAG_ACTIVITY_NEW_TASK
        computeLaunchingTaskFlags();
        //检测当前栈
        computeSourceStack();

        //最终确定Task启动方式
        mIntent.setFlags(mLaunchFlags);
			
		// 判断是否应将新Activity插入到现有任务栈中
        // 如果不需要,则返回null,如果需要,则返回该任务栈信息

        ActivityRecord reusedActivity = getReusableIntentActivity();
    	//判断是否可以重新利用
        if (reusedActivity != null) {
        	...............
            if (reusedActivity.getTask().intent == null) {
            	//如果历史记录中有匹配的任务,找出应该将哪个放到前面   
            reusedActivity = setTargetStackAndMoveToFrontIfNeeded(reusedActivity);
                //设置为当前栈顶或最先创建的活动
            setTaskFromIntentActivity(reusedActivity);

        }
       //恢复当前focus的堆栈stack中的顶端活动对象top activity
       mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack,                                                                            mStartActivity, mOptions);

        return START_SUCCESS;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 为待启动的ActivityRecord找到他对应的TaskRecord和ActivityStack;
2.2.3 恢复当前Stack中的顶端活动对象

ActivityStackSupervisor#resumeFocusedStackTopActivityLocked

源码位置frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

boolean resumeFocusedStackTopActivityLocked(ActivityStack targetStack,
                                             ActivityRecord target,
                                             ActivityOptions targetOptions) {
        //如果目标栈不为空且是焦点栈,则直接将准备的activityRecord设置为栈顶活动
     	if (targetStack != null && isFocusedStack(targetStack)) {
            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
     	//获取能运行的栈中的栈顶ActivityRecord
        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
        if (r == null || r.state != RESUMED) {
            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
        } else if (r.state == RESUMED) {
            // Kick off any lingering app transitions form the MoveTaskToFront operation.
            mFocusedStack.executeAppTransition(targetOptions);
        }
        return false;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

ActivityStack#resumeTopActivityUncheckedLocked

ActivityStack源码路径 frameworks/base/services/core/java/com/android/server/am/ActivityStack.java

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        boolean result = false;
     	//设置栈顶Activity
        result = resumeTopActivityInnerLocked(prev, options);
        return result;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
2.2.4 暂停上一个Activity,并启动准备好的Activity
 private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
		//暂停失去焦点的活动对象 如果是启动Launcher进程 这里不会做操作因为launcher之前没有activity
        boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
        if (mResumedActivity != null) {
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Pausing " + mResumedActivity);
				//准备暂定活动这里准备暂停的是Launcher
            pausing |= startPausingLocked(userLeaving, false, next, false);
        }       
     	// 启动Activity
        mStackSupervisor.startSpecificActivityLocked(next, true, true);  
        return true;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 暂停上一个Activity
  • 并启动准备好的Activity

3.1 启动Activity 判断进程是否存在

启动准备好的Activity

ActivityStackSupervisor.startSpecificActivityLocked

void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
        // Is this activity's application already running? 此活动的应用程序是否已在运行?
       //1 获取即将启动的Activiy所在的应用程序进程
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid, true);
        r.getStack().setLaunchTime(r);
		//2 判断是否运行 运行 则执行 realStartActivityLocked
        if (app != null && app.thread != null) {
            try {
                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                        || !"android".equals(r.info.packageName)) {
                    app.addPackage(r.info.packageName,
                                   r.info.applicationInfo.versionCode,
                                   mService.mProcessStats);
                }
                //3 启动Activity
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                
            }
        }
     	//4 若没运行则 创建新的进程
        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                "activity", r.intent.getComponent(), false, false, true);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 获取即将启动的Activiy所在的应用程序进程

    • 若存在启动Activity

      • 这里是在应用内启动,所以上面应用程序进程是存在的

        执行ActivityStackSupervisor#realStartActivityLocked

    • 不存在则创建进程,这里启动的是MainActivity 肯定是不存在的

4 启动Activity

#### 4.1 AMS 通知给ActivityThread

realStartActivityLocked

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
    		................
           //在这里AMS通过ApplicationThread的binder对象,通过Binder驱动, 执行到了ActivityThread里的scheduleLaunchActivity
            app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                    System.identityHashCode(r), r.info,
                    mergedConfiguration.getGlobalConfiguration(),
                    mergedConfiguration.getOverrideConfiguration(), r.compat,
                    r.launchedFromPackage, task.voiceInteractor, 
                    app.repProcState, r.icicle,
                    r.persistentState, results, newIntents, !andResume,
                    mService.isNextTransitionForward(), profilerInfo);
      
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • AMS通过ApplicationThread的binder对象,通过Binder驱动, 执行到了ActivityThread里的scheduleLaunchActivity
4.2 ActivityThread启动Activity
4.2.1 通过Handler 发送 LAUNCH_ACTIVITY 启动

ActivityThread#scheduleLaunchActivity

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Configuration curConfig,
                Configuration overrideConfig,
                CompatibilityInfo compatInfo,
                String referrer,
                IVoiceInteractor voiceInteractor,
                int procState, Bundle state,
                PersistableBundle persistentState,
                List<ResultInfo> pendingResults,
                List<ReferrerIntent> pendingNewIntents,
                boolean notResumed,boolean isForward, 
                ProfilerInfo profilerInfo) {

            updateProcessState(procState, false);

            ActivityClientRecord r = new ActivityClientRecord();
     		// 发送一个LAUNCH_ACTIVITY 并将活动传递
            sendMessage(H.LAUNCH_ACTIVITY, r);
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
4.2.2 Handler接收消息
public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
                case LAUNCH_ACTIVITY: {
                   
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    //调用HandleLauncheActivity启动
                    handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
               
                } break;
            }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
4.2.3 处理消息

handleLaunchActivity

 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
        // 创建Activity对象
        Activity a = performLaunchActivity(r, customIntent);

        if (a != null) {
            //通知对象可见
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed,
                                 r.lastProcessedSeq, reason);
        } else {
            //创建失败则关闭该activity
            try {
                ActivityManager.getService()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                            Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
4.2.3.1 创建activity,执行Activity 的OnCreate

performLaunchActivity

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");

       	//收集Activity相关信息,包信息,组件信息
        ComponentName component = r.intent.getComponent();
        if (component == null) {
            component = r.intent.resolveActivity(
                mInitialApplication.getPackageManager());
            r.intent.setComponent(component);
        }
        //创建上下文
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
        	//通过类加载机制将Activity加载进来
            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) {
           ....
        }
		.....................
		//声明Window对象
		Window window = null;
        try {
        	//创建Application对象 当前进程内全局唯一
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            if (activity != null) {
               //attach内部首先调用了attachBaseContex绑定上下文信息,
                //创建PhoneWindow并给其设置Windowmanager处理
                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);
                //通过mInstrumentation执行Activity的onCreate方法
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
     .............
            }

        } catch (SuperNotCalledException e) {
          .................
        }
        return activity;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 通过类加载机制加载activity

  • 通过调用Activity#attach 绑定上下文信息,创建PhoneWindow给Windowmanager处理

  • 并通过Instrumentation的callActivityOnCreate方法来执行Activity的OnCreate

  • 在oncreate中执行setContentView创建布局 在ActivityResume时 将布局添加到window

  • callActivityOnCreate

    public void callActivityOnCreate(Activity activity, Bundle icicle,
       PersistableBundle persistentState) {
    prePerformCreate(activity);
    activity.performCreate(icicle, persistentState);
    postPerformCreate(activity);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 内部通过 Activity#performCreate 执行Activity的onCreate
    final void performCreate(Bundle icicle) {
         restoreHasCurrentPermissionRequest(icicle);
        	// 最后回调OnCrate方法 
         onCreate(icicle);
         mActivityTransitionState.readState(icicle);
         performCreateCommon();
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    4.2.3.2 执行onResume

    在这里涉及到显示布局,也是就是Activtiy绘制这里仅点出 并不分析

    在4.2.3.1中可知创建的Activity不为空.所以4.2.3后面执行了handleLaunchActivity

    final void handleResumeActivity(IBinder token,
                boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
            ActivityClientRecord r = mActivities.get(token);
            if (!checkAndUpdateLifecycleSeq(seq, r, "resumeActivity")) {
                return;
            }
            r = performResumeActivity(token, clearHide, reason);
    		//.....................
            if (r != null) {
                final Activity a = r.activity;
    			//.........  
                //显示onCreate setContentView 创建的布局 通过wm.addview
                if (r.window == null && !a.mFinished && willBeVisible) {
                    r.window = r.activity.getWindow();
                    View decor = r.window.getDecorView();
                    decor.setVisibility(View.INVISIBLE);
                    ViewManager wm = a.getWindowManager();
                    WindowManager.LayoutParams l = r.window.getAttributes();
                    a.mDecor = decor;
                    l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                    l.softInputMode |= forwardBit;
                    //........
                    if (a.mVisibleFromClient) {
                        if (!a.mWindowAdded) {
                            a.mWindowAdded = true;
                            wm.addView(decor, l);
                        } 
                    }
                //...........
                } 
                //通知AMS 该activity 已经可见并了
                if (reallyResume) {
                    try {
                        ActivityManager.getService().activityResumed(token);
                    } catch (RemoteException ex) {
                        throw ex.rethrowFromSystemServer();
                    }
                }
            } 
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 上面代码主要作用
      • 将onCreate创建的布局添加到window上展示
      • 并通知AMS 该Activity已经可见了
4.2.3.2 执行onResume

在这里涉及到显示布局,也是就是Activtiy绘制这里仅点出 并不分析

在4.2.3.1中可知创建的Activity不为空.所以4.2.3后面执行了handleResumeActivity

final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
        ActivityClientRecord r = mActivities.get(token);
        if (!checkAndUpdateLifecycleSeq(seq, r, "resumeActivity")) {
            return;
        }
        r = performResumeActivity(token, clearHide, reason);
		//.....................
        if (r != null) {
            final Activity a = r.activity;
			//.........  
            //显示onCreate setContentView 创建的布局 通过wm.addview
            if (r.window == null && !a.mFinished && willBeVisible) {
                r.window = r.activity.getWindow();
                View decor = r.window.getDecorView();
                decor.setVisibility(View.INVISIBLE);
                ViewManager wm = a.getWindowManager();
                WindowManager.LayoutParams l = r.window.getAttributes();
                a.mDecor = decor;
                l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                l.softInputMode |= forwardBit;
                //........
                if (a.mVisibleFromClient) {
                    if (!a.mWindowAdded) {
                        a.mWindowAdded = true;
                        wm.addView(decor, l);
                    } 
                }
            //...........
            } 
            //通知AMS 该activity 已经可见并了
            if (reallyResume) {
                try {
                    ActivityManager.getService().activityResumed(token);
                } catch (RemoteException ex) {
                    throw ex.rethrowFromSystemServer();
                }
            }
        } 
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 上面代码主要作用
    • 将onCreate创建的布局添加到window上展示
    • 并通知AMS 该Activity已经可见了

至此Activity启动结束。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/680191
推荐阅读
相关标签
  

闽ICP备14008679号