Android 源码分析(二) Activity 启动分析

//file:android-8.0.0_r1\frameworks\base\core\java\android\app\Activity.java

	/**
	*	startActivity最终都调用了startActivityForResult方法
	*/
	@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 {
            // Note we want to go through this call for compatibility with
            // applications that may have overridden the method.
            startActivityForResult(intent, -1);
        }
    }
	@Override
    public void startActivityForResult(
            String who, Intent intent, int requestCode, @Nullable Bundle options) {
        Uri referrer = onProvideReferrer();
        if (referrer != null) {
            intent.putExtra(Intent.EXTRA_REFERRER, referrer);
        }
        options = transferSpringboardActivityOptions(options);
		//TODO 
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, who,
                intent, requestCode, options);
        if (ar != null) {
            mMainThread.sendActivityResult(
                mToken, who, requestCode,
                ar.getResultCode(), ar.getResultData());
        }
        cancelInputsAndStartExitTransition(options);
    }

  

//android-8.0.0_r1\frameworks\base\core\java\android\app\Instrumentation.java

public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, String target,
        Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
        if (mActivityMonitors != null) {
            synchronized (mSync) {
                final int N = mActivityMonitors.size();
                for (int i=0; i<N; i++) {
                    final ActivityMonitor am = mActivityMonitors.get(i);
                    ActivityResult result = null;
                    if (am.ignoreMatchingSpecificIntents()) {
                        result = am.onStartActivity(intent);
                    }
                    if (result != null) {
                        am.mHits++;
                        return result;
                    } else if (am.match(who, null, intent)) {
                        am.mHits++;
                        if (am.isBlocking()) {
                            return requestCode >= 0 ? am.getResult() : null;
                        }
                        break;
                    }
                }
            }
        }
        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess(who);
			// 打开Activity,跨进程调用ActivityManagerService的startActivity方法
            int result = ActivityManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target, requestCode, 0, null, options);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

  

//android-8.0.0_r1\frameworks\base\core\java\android\app\ActivityManager.java
	public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }

    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;
                }
            };

  

//android-8.0.0_r1\frameworks\base\services\core\java\com\android\server\am\ActivityManagerService.java

	/**
	* ActivityManager.getService()返回的是ActivityManagerService的远程Binder对象。
	* 通过远程Binder对象调用ActivityManagerService的startActivity方法。
	*/
   public class ActivityManagerService extends IActivityManager.Stub

   @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());
   }

   final int startActivity(Intent intent, ActivityStackSupervisor.ActivityContainer container) {
	   enforceNotIsolatedCaller("ActivityContainer.startActivity");
	   final int userId = mUserController.handleIncomingUser(Binder.getCallingPid(),
			   Binder.getCallingUid(), mStackSupervisor.mCurrentUser, false,
			   ActivityManagerService.ALLOW_FULL_ONLY, "ActivityContainer", null);

	   // TODO: Switch to user app stacks here.
	   String mimeType = intent.getType();
	   final Uri data = intent.getData();
	   if (mimeType == null && data != null && "content".equals(data.getScheme())) {
		   mimeType = getProviderMimeType(data, userId);
	   }
	   container.checkEmbeddedAllowedInner(userId, intent, mimeType);

	   intent.addFlags(FORCE_NEW_TASK_FLAGS);
	   //TODO
	   return mActivityStarter.startActivityMayWait(null, -1, null, intent, mimeType, null, null,
			   null, null, 0, 0, null, null, null, null, false, userId, container, null,
			   "startActivity");
   }

   @Override
   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) {
	   enforceNotIsolatedCaller("startActivity");
	   userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
			   userId, false, ALLOW_FULL_ONLY, "startActivity", null);
	   // TODO: Switch to user app stacks here.
	   return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
			   resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
			   profilerInfo, null, null, bOptions, false, userId, null, null,
			   "startActivityAsUser");
   }

  

//	android-8.0.0_r1\frameworks\base\services\core\java\com\android\server\am\ActivityStarter.java

	/**
	* ActivityManagerService的startActivity启动过程又转移到mStackSupervisor.startActivityMayWait函数了。
	* 而mStackSupervisor是ActivityStackSupervisor类的对象
	*/

	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) {
			====省略=====
			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);

			====省略=====
			}

		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) {

        if (TextUtils.isEmpty(reason)) {
            throw new IllegalArgumentException("Need to specify a reason.");
        }
        mLastStartReason = reason;
        mLastStartActivityTimeMs = System.currentTimeMillis();
        mLastStartActivityRecord[0] = null;

        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);

        if (outActivity != null) {
            // mLastStartActivityRecord[0] is set in the call to startActivity above.
            outActivity[0] = mLastStartActivityRecord[0];
        }
        return mLastStartActivityResult;
    }

		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) {

			====省略=====
			return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,
                options, inTask, outActivity);

       }

	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();
			//TODO
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity);
        } finally {
            // If we are not able to proceed, disassociate the activity from the task. Leaving an
            // activity in an incomplete state can lead to issues, such as performing operations
            // without a window container.
            if (!ActivityManager.isStartResultSuccessful(result)
                    && mStartActivity.getTask() != null) {
                mStartActivity.getTask().removeActivity(mStartActivity);
            }
            mService.mWindowManager.continueSurfaceLayout();
        }

        postStartActivityProcessing(r, result, mSupervisor.getLastStack().mStackId,  mSourceRecord,
                mTargetStack);

        return result;
    }

  

//	android-8.0.0_r1\frameworks\base\services\core\java\com\android\server\am\ActivityStackSupervisor.java		

	/**
	* app.thread的类型为IApplicationThread
	*/
	final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
            ====省略=====
			app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
								System.identityHashCode(r), r.info,
								// TODO: Have this take the merged configuration instead of separate global and
								// override configs.
								mergedConfiguration.getGlobalConfiguration(),
								mergedConfiguration.getOverrideConfiguration(), r.compat,
								r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
								r.persistentState, results, newIntents, !andResume,
								mService.isNextTransitionForward(), profilerInfo);

	  ====省略=====

    }

  

//android-8.0.0_r1\frameworks\base\core\tests\coretests\src\android\app\activity\ActivityThread.java
	private class ApplicationThread extends IApplicationThread.Stub {

	@Override
	   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();

		   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);

		   sendMessage(H.LAUNCH_ACTIVITY, r);
	   }

	}


	private class H extends Handler {

	/**
	* 主要是进行系统之间的消息通信的,并联系着Activity各个生命周期函数
	*/
	public void handleMessage(Message msg) {
		if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
		switch (msg.what) {
			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;
			case RELAUNCH_ACTIVITY: {
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
				ActivityClientRecord r = (ActivityClientRecord)msg.obj;
				handleRelaunchActivity(r);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
			} break;
			case PAUSE_ACTIVITY: {
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
				SomeArgs args = (SomeArgs) msg.obj;
				handlePauseActivity((IBinder) args.arg1, false,
						(args.argi1 & USER_LEAVING) != 0, args.argi2,
						(args.argi1 & DONT_REPORT) != 0, args.argi3);
				maybeSnapshot();
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
			} break;
			case PAUSE_ACTIVITY_FINISHING: {
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
				SomeArgs args = (SomeArgs) msg.obj;
				handlePauseActivity((IBinder) args.arg1, true, (args.argi1 & USER_LEAVING) != 0,
						args.argi2, (args.argi1 & DONT_REPORT) != 0, args.argi3);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
			} break;
			case STOP_ACTIVITY_SHOW: {
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStop");
				SomeArgs args = (SomeArgs) msg.obj;
				handleStopActivity((IBinder) args.arg1, true, args.argi2, args.argi3);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
			} break;
			case STOP_ACTIVITY_HIDE: {
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStop");
				SomeArgs args = (SomeArgs) msg.obj;
				handleStopActivity((IBinder) args.arg1, false, args.argi2, args.argi3);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
			} break;
			case SHOW_WINDOW:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityShowWindow");
				handleWindowVisibility((IBinder)msg.obj, true);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case HIDE_WINDOW:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityHideWindow");
				handleWindowVisibility((IBinder)msg.obj, false);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case RESUME_ACTIVITY:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
				SomeArgs args = (SomeArgs) msg.obj;
				handleResumeActivity((IBinder) args.arg1, true, args.argi1 != 0, true,
						args.argi3, "RESUME_ACTIVITY");
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case SEND_RESULT:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityDeliverResult");
				handleSendResult((ResultData)msg.obj);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case DESTROY_ACTIVITY:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityDestroy");
				handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
						msg.arg2, false);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case BIND_APPLICATION:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
				AppBindData data = (AppBindData)msg.obj;
				handleBindApplication(data);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case EXIT_APPLICATION:
				if (mInitialApplication != null) {
					mInitialApplication.onTerminate();
				}
				Looper.myLooper().quit();
				break;
			case NEW_INTENT:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityNewIntent");
				handleNewIntent((NewIntentData)msg.obj);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case RECEIVER:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
				handleReceiver((ReceiverData)msg.obj);
				maybeSnapshot();
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case CREATE_SERVICE:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));
				handleCreateService((CreateServiceData)msg.obj);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case BIND_SERVICE:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
				handleBindService((BindServiceData)msg.obj);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case UNBIND_SERVICE:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");
				handleUnbindService((BindServiceData)msg.obj);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case SERVICE_ARGS:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceStart: " + String.valueOf(msg.obj)));
				handleServiceArgs((ServiceArgsData)msg.obj);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case STOP_SERVICE:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
				handleStopService((IBinder)msg.obj);
				maybeSnapshot();
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case CONFIGURATION_CHANGED:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "configChanged");
				mCurDefaultDisplayDpi = ((Configuration)msg.obj).densityDpi;
				mUpdatingSystemConfig = true;
				try {
					handleConfigurationChanged((Configuration) msg.obj, null);
				} finally {
					mUpdatingSystemConfig = false;
				}
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case CLEAN_UP_CONTEXT:
				ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
				cci.context.performFinalCleanup(cci.who, cci.what);
				break;
			case GC_WHEN_IDLE:
				scheduleGcIdler();
				break;
			case DUMP_SERVICE:
				handleDumpService((DumpComponentInfo)msg.obj);
				break;
			case LOW_MEMORY:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "lowMemory");
				handleLowMemory();
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case ACTIVITY_CONFIGURATION_CHANGED:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityConfigChanged");
				handleActivityConfigurationChanged((ActivityConfigChangeData) msg.obj,
						INVALID_DISPLAY);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case ACTIVITY_MOVED_TO_DISPLAY:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityMovedToDisplay");
				handleActivityConfigurationChanged((ActivityConfigChangeData) msg.obj,
						msg.arg1 /* displayId */);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case PROFILER_CONTROL:
				handleProfilerControl(msg.arg1 != 0, (ProfilerInfo)msg.obj, msg.arg2);
				break;
			case CREATE_BACKUP_AGENT:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupCreateAgent");
				handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case DESTROY_BACKUP_AGENT:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupDestroyAgent");
				handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case SUICIDE:
				Process.killProcess(Process.myPid());
				break;
			case REMOVE_PROVIDER:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "providerRemove");
				completeRemoveProvider((ProviderRefCount)msg.obj);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case ENABLE_JIT:
				ensureJitEnabled();
				break;
			case DISPATCH_PACKAGE_BROADCAST:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastPackage");
				handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case SCHEDULE_CRASH:
				throw new RemoteServiceException((String)msg.obj);
			case DUMP_HEAP:
				handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
				break;
			case DUMP_ACTIVITY:
				handleDumpActivity((DumpComponentInfo)msg.obj);
				break;
			case DUMP_PROVIDER:
				handleDumpProvider((DumpComponentInfo)msg.obj);
				break;
			case SLEEPING:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "sleeping");
				handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case SET_CORE_SETTINGS:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setCoreSettings");
				handleSetCoreSettings((Bundle) msg.obj);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case UPDATE_PACKAGE_COMPATIBILITY_INFO:
				handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
				break;
			case TRIM_MEMORY:
				Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "trimMemory");
				handleTrimMemory(msg.arg1);
				Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
				break;
			case UNSTABLE_PROVIDER_DIED:
				handleUnstableProviderDied((IBinder)msg.obj, false);
				break;
			case REQUEST_ASSIST_CONTEXT_EXTRAS:
				handleRequestAssistContextExtras((RequestAssistContextExtras)msg.obj);
				break;
			case TRANSLUCENT_CONVERSION_COMPLETE:
				handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);
				break;
			case INSTALL_PROVIDER:
				handleInstallProvider((ProviderInfo) msg.obj);
				break;
			case ON_NEW_ACTIVITY_OPTIONS:
				Pair<IBinder, ActivityOptions> pair = (Pair<IBinder, ActivityOptions>) msg.obj;
				onNewActivityOptions(pair.first, pair.second);
				break;
			case CANCEL_VISIBLE_BEHIND:
				handleCancelVisibleBehind((IBinder) msg.obj);
				break;
			case BACKGROUND_VISIBLE_BEHIND_CHANGED:
				handleOnBackgroundVisibleBehindChanged((IBinder) msg.obj, msg.arg1 > 0);
				break;
			case ENTER_ANIMATION_COMPLETE:
				handleEnterAnimationComplete((IBinder) msg.obj);
				break;
			case START_BINDER_TRACKING:
				handleStartBinderTracking();
				break;
			case STOP_BINDER_TRACKING_AND_DUMP:
				handleStopBinderTrackingAndDump((ParcelFileDescriptor) msg.obj);
				break;
			case MULTI_WINDOW_MODE_CHANGED:
				handleMultiWindowModeChanged((IBinder) ((SomeArgs) msg.obj).arg1,
						((SomeArgs) msg.obj).argi1 == 1,
						(Configuration) ((SomeArgs) msg.obj).arg2);
				break;
			case PICTURE_IN_PICTURE_MODE_CHANGED:
				handlePictureInPictureModeChanged((IBinder) ((SomeArgs) msg.obj).arg1,
						((SomeArgs) msg.obj).argi1 == 1,
						(Configuration) ((SomeArgs) msg.obj).arg2);
				break;
			case LOCAL_VOICE_INTERACTION_STARTED:
				handleLocalVoiceInteractionStarted((IBinder) ((SomeArgs) msg.obj).arg1,
						(IVoiceInteractor) ((SomeArgs) msg.obj).arg2);
				break;
			case ATTACH_AGENT:
				handleAttachAgent((String) msg.obj);
				break;
			case APPLICATION_INFO_CHANGED:
				mUpdatingSystemConfig = true;
				try {
					handleApplicationInfoChanged((ApplicationInfo) msg.obj);
				} finally {
					mUpdatingSystemConfig = false;
				}
				break;
		}
		Object obj = msg.obj;
		if (obj instanceof SomeArgs) {
			((SomeArgs) obj).recycle();
		}
		if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
	}

}


private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();
        mSomeActivitiesChanged = true;

        if (r.profilerInfo != null) {
            mProfiler.setProfiler(r.profilerInfo);
            mProfiler.startProfiling();
        }

        // Make sure we are running with the most recent config.
        handleConfigurationChanged(null, null);

        if (localLOGV) Slog.v(
            TAG, "Handling launch of " + r);

        // Initialize before creating the activity
        WindowManagerGlobal.initialize();

        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();
            }
        }
    }

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

        ActivityInfo aInfo = r.activityInfo;
        if (r.packageInfo == null) {
            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                    Context.CONTEXT_INCLUDE_CODE);
        }

        ComponentName component = r.intent.getComponent();
        if (component == null) {
            component = r.intent.resolveActivity(
                mInitialApplication.getPackageManager());
            r.intent.setComponent(component);
        }

        if (r.activityInfo.targetActivity != null) {
            component = new ComponentName(r.activityInfo.packageName,
                    r.activityInfo.targetActivity);
        }

        ContextImpl appContext = createBaseContextForActivity(r);
        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);
            }
        }

        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
            if (localLOGV) Slog.v(
                    TAG, r + ": app=" + app
                    + ", appName=" + app.getPackageName()
                    + ", pkg=" + r.packageInfo.getPackageName()
                    + ", comp=" + r.intent.getComponent().toShortString()
                    + ", dir=" + r.packageInfo.getAppDir());

            if (activity != null) {
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                if (r.overrideConfig != null) {
                    config.updateFrom(r.overrideConfig);
                }
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                        + r.activityInfo.name + " with config " + config);
                Window window = null;
                if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                    window = r.mPendingRemoveWindow;
                    r.mPendingRemoveWindow = null;
                    r.mPendingRemoveWindowManager = null;
                }
                appContext.setOuterContext(activity);
                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);

                if (customIntent != null) {
                    activity.mIntent = customIntent;
                }
                r.lastNonConfigurationInstances = null;
                checkAndBlockForNetworkAccess();
                activity.mStartedActivity = false;
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    activity.setTheme(theme);
                }

                activity.mCalled = false;
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                if (!activity.mCalled) {
                    throw new SuperNotCalledException(
                        "Activity " + r.intent.getComponent().toShortString() +
                        " did not call through to super.onCreate()");
                }
                r.activity = activity;
                r.stopped = true;
                if (!r.activity.mFinished) {
                    activity.performStart();
                    r.stopped = false;
                }
                if (!r.activity.mFinished) {
                    if (r.isPersistable()) {
                        if (r.state != null || r.persistentState != null) {
                            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                                    r.persistentState);
                        }
                    } else if (r.state != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                    }
                }
                if (!r.activity.mFinished) {
                    activity.mCalled = false;
                    if (r.isPersistable()) {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state,
                                r.persistentState);
                    } else {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state);
                    }
                    if (!activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onPostCreate()");
                    }
                }
            }
            r.paused = true;

            mActivities.put(r.token, r);

        } catch (SuperNotCalledException e) {
            throw e;

        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to start activity " + component
                    + ": " + e.toString(), e);
            }
        }

        return activity;
    }

  

//android-8.0.0_r1\frameworks\base\core\java\android\app\Instrumentation.java
	public void callActivityOnCreate(Activity activity, Bundle icicle,
            PersistableBundle persistentState) {
        prePerformCreate(activity);
        activity.performCreate(icicle, persistentState);
        postPerformCreate(activity);
    }

  

//android-8.0.0_r1\frameworks\base\core\java\android\app\Activity.java
	final void performCreate(Bundle icicle, PersistableBundle persistentState) {
	   restoreHasCurrentPermissionRequest(icicle);
	   onCreate(icicle, persistentState);
	   mActivityTransitionState.readState(icicle);
	   performCreateCommon();
   }

	@MainThread
    @CallSuper
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);

        if (getApplicationInfo().targetSdkVersion > O && mActivityInfo.isFixedOrientation()) {
            final TypedArray ta = obtainStyledAttributes(com.android.internal.R.styleable.Window);
            final boolean isTranslucentOrFloating = ActivityInfo.isTranslucentOrFloating(ta);
            ta.recycle();

            if (isTranslucentOrFloating) {
                throw new IllegalStateException(
                        "Only fullscreen opaque activities can request orientation");
            }
        }

        if (mLastNonConfigurationInstances != null) {
            mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
        }
        if (mActivityInfo.parentActivityName != null) {
            if (mActionBar == null) {
                mEnableDefaultActionBarUp = true;
            } else {
                mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
            }
        }
        if (savedInstanceState != null) {
            mAutoFillResetNeeded = savedInstanceState.getBoolean(AUTOFILL_RESET_NEEDED, false);
            mLastAutofillId = savedInstanceState.getInt(LAST_AUTOFILL_ID,
                    View.LAST_APP_AUTOFILL_ID);

            if (mAutoFillResetNeeded) {
                getAutofillManager().onCreate(savedInstanceState);
            }

            Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
            mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
                    ? mLastNonConfigurationInstances.fragments : null);
        }
        mFragments.dispatchCreate();
        getApplication().dispatchActivityCreated(this, savedInstanceState);
        if (mVoiceInteractor != null) {
            mVoiceInteractor.attachActivity(this);
        }
        mCalled = true;
    }

  ========================================================================

//android-8.0.0_r1\frameworks\base\core\tests\coretests\src\android\app\activity\ActivityThread.java
/**
* ActivityThread 并不是一个线程类,从它的定义可以看出它并非继承自Thread类.
* Android应用程序框架层创建的应用程序的入口函数是ActivityThread.main()。
* ActivityThread的main函数的主要作用就是开启消息循环,处理UI线程中各种消息。
*/
public final class ActivityThread {

	public static void main(String[] args) {
		Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
		SamplingProfilerIntegration.start();

		// CloseGuard defaults to true and can be quite spammy.  We
		// disable it here, but selectively enable it later (via
		// StrictMode) on debug builds, but using DropBox, not logs.
		CloseGuard.setEnabled(false);

		Environment.initForCurrentUser();

		// Set the reporter for event logging in libcore
		EventLogger.setReporter(new EventLoggingReporter());

		// Make sure TrustedCertificateStore looks in the right place for CA certificates
		final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
		TrustedCertificateStore.setDefaultUserDirectory(configDir);

		Process.setArgV0("<pre-initialized>");

		Looper.prepareMainLooper();

		ActivityThread thread = new ActivityThread();
		thread.attach(false);

		if (sMainThreadHandler == null) {
			sMainThreadHandler = thread.getHandler();
		}

		if (false) {
			Looper.myLooper().setMessageLogging(new
					LogPrinter(Log.DEBUG, "ActivityThread"));
		}

		// End of event ActivityThreadMain.
		Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
		// 轮询处理UI线程的消息
		Looper.loop();

		throw new RuntimeException("Main thread loop unexpectedly exited");
	}
}


/**
*它是Activity描述的类,对Activity进行了高度抽象。它是ActivityThread的静态final内部类。 
* 每个Activity被创建出来的时候,都对应着一个ActivityClientRecord,用于记录Activity的信息
*/
static final class ActivityClientRecord {
        IBinder token;
        int ident;
        Intent intent;
        String referrer;
        IVoiceInteractor voiceInteractor;
        Bundle state;
        PersistableBundle persistentState;
        Activity activity;
        Window window;
        Activity parent;
        String embeddedID;
        Activity.NonConfigurationInstances lastNonConfigurationInstances;
        boolean paused;
        boolean stopped;
        boolean hideForNow;
        Configuration newConfig;
        Configuration createdConfig;
        Configuration overrideConfig;
        // Used for consolidating configs before sending on to Activity.
        private Configuration tmpConfig = new Configuration();
        // Callback used for updating activity override config.
        ViewRootImpl.ActivityConfigCallback configCallback;
        ActivityClientRecord nextIdle;

        ProfilerInfo profilerInfo;

        ActivityInfo activityInfo;
        CompatibilityInfo compatInfo;
        LoadedApk packageInfo;

        List<ResultInfo> pendingResults;
        List<ReferrerIntent> pendingIntents;

        boolean startsNotResumed;
        boolean isForward;
        int pendingConfigChanges;
        boolean onlyLocalRequest;

        Window mPendingRemoveWindow;
        WindowManager mPendingRemoveWindowManager;
        boolean mPreserveWindow;

        // Set for relaunch requests, indicates the order number of the relaunch operation, so it
        // can be compared with other lifecycle operations.
        int relaunchSeq = 0;

        // Can only be accessed from the UI thread. This represents the latest processed message
        // that is related to lifecycle events/
        int lastProcessedSeq = 0;

        ActivityClientRecord() {...}
}

  

 

posted @ 2018-06-24 03:26  FreeFunCode  阅读(1423)  评论(0编辑  收藏  举报