AMS啓動的上半段,從Activty的startActivty啓動Activity過程

在這裏插入圖片描述

Activity#startActivity

//從Activity的startActivity方法爲起點分析

//Activity#startActivity方法
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);
	}
}
//Activity#startActivityForResult方法
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options)
{
	if (mParent == null) {
		Instrumentation.ActivityResult ar =
        //調用Instrumentation的execStartActivity方法 mInstrumentation 是在ActivtyThread attach方法時候創建的實例
		     mInstrumentation.execStartActivity(
		          this, mMainThread.getApplicationThread(), mToken, this,
		          intent, requestCode, options);
		...
  }
}
Instrumentation#execStartActivity
//Instrumentation 的 execStartActivity方法
public ActivityResult execStartActivity(
     Context who, IBinder contextThread, IBinder token, Activity target,
     Intent intent, int requestCode, Bundle options)
{

	try {
		intent.migrateExtraStreamToClipData();
		intent.prepareToLeaveProcess();
    //調用ActivityManagerNative 的getDefault 獲取單例,調用的startActivity方法
		int result = ActivityManagerNative.getDefault()
		             .startActivity(whoThread, who.getBasePackageName(), intent,
		                            intent.resolveTypeIfNeeded(who.getContentResolver()),
		                            token, target != null ? target.mEmbeddedID : null,
		                            requestCode, 0, null, options);
		checkStartActivityResult(result, intent);
	} catch (RemoteException e) {
	}
	return null;
}

ActivityManagerNative#getDefault
//獲取單例
static public IActivityManager getDefault()
{
	return gDefault.get();
}

//查看單例方法
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>()
{
	protected IActivityManager create() {
    //獲取binder的activity服務
		IBinder b = ServiceManager.getService("activity");
		if (false) {
			Log.v("ActivityManager", "default service binder = " + b);
		}
    //通過asInterface獲取IActivityManager
		IActivityManager am = asInterface(b);
		if (false) {
			Log.v("ActivityManager", "default service = " + am);
		}
		return am;
	}
};
//asInterface
static public IActivityManager asInterface(IBinder obj)
{
	if (obj == null) {
		return null;
	}
  //查詢本地是否存在IActivityManager接口,如果存在直接返回
  IActivityManager in =
	     (IActivityManager)obj.queryLocalInterface(descriptor);
	if (in != null) {
		return in;
	}
  //沒有,則創建一個ActivityManagerProxy 實例
	return new ActivityManagerProxy(obj);
}

ActivityManagerProxy
//ActivityManagerProxy是ActivityManagerNative的一個內部類 所以剛纔ActivityManagerNative.getDefault()
//             .startActivity 實際上調用的是ActivityManagerProxy的startActivity
class ActivityManagerProxy implements IActivityManager
{
    public ActivityManagerProxy(IBinder remote)
    {
        mRemote = remote;
    }

    public IBinder asBinder()
    {
        return mRemote;
    }
    //startActivity 從此方法看出,一個binder通信的Client端
    public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
            String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IActivityManager.descriptor);
        data.writeStrongBinder(caller != null ? caller.asBinder() : null);
        data.writeString(callingPackage);
        intent.writeToParcel(data, 0);
        data.writeString(resolvedType);
        data.writeStrongBinder(resultTo);
        data.writeString(resultWho);
        data.writeInt(requestCode);
        data.writeInt(startFlags);
        if (profilerInfo != null) {
            data.writeInt(1);
            profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
        } else {
            data.writeInt(0);
        }
        if (options != null) {
            data.writeInt(1);
            options.writeToParcel(data, 0);
        } else {
            data.writeInt(0);
        }
        //通過下面的transact方法的定義START_ACTIVITY_TRANSACTION是一個特徵Code,通過START_ACTIVITY_TRANSACTION我們可以找到他的服務端
        mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
        reply.readException();
        int result = reply.readInt();
        reply.recycle();
        data.recycle();
        return result;
    }

    /**
    * Perform a generic operation with the object.
    *
    * @param code The action to perform.  This should
    * be a number between {@link #FIRST_CALL_TRANSACTION} and
    * {@link #LAST_CALL_TRANSACTION}.
    * @param data Marshalled data to send to the target.  Must not be null.
    * If you are not sending any data, you must create an empty Parcel
    * that is given here.
    * @param reply Marshalled data to be received from the target.  May be
    * null if you are not interested in the return value.
    * @param flags Additional operation flags.  Either 0 for a normal
    * RPC, or {@link #FLAG_ONEWAY} for a one-way RPC.
    */

/*public boolean transact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException;*/

    public int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent,
            String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options,
            int userId) throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IActivityManager.descriptor);
        data.writeStrongBinder(caller != null ? caller.asBinder() : null);
        data.writeString(callingPackage);
        intent.writeToParcel(data, 0);
        data.writeString(resolvedType);
        data.writeStrongBinder(resultTo);
        data.writeString(resultWho);
        data.writeInt(requestCode);
        data.writeInt(startFlags);
        if (profilerInfo != null) {
            data.writeInt(1);
            profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
        } else {
            data.writeInt(0);
        }
        if (options != null) {
            data.writeInt(1);
            options.writeToParcel(data, 0);
        } else {
            data.writeInt(0);
        }
        data.writeInt(userId);
        mRemote.transact(START_ACTIVITY_AS_USER_TRANSACTION, data, reply, 0);
        reply.readException();
        int result = reply.readInt();
        reply.recycle();
        data.recycle();
        return result;
    }
    ...
}

Binder服務端 ActivityManagerNative
//通過AcitivityManagerProxy的startActivityAsUser 發送Binder請求
//ActivityManagerNative de onTransact 進行接受 調用自己的startActivity方法
//這裏實質上是ActivityManagerService的接受  ActivityManagerService繼承ActivityManagerNative
@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
	switch (code) {
	case START_ACTIVITY_TRANSACTION: {
		data.enforceInterface(IActivityManager.descriptor);
		IBinder b = data.readStrongBinder();
		IApplicationThread app = ApplicationThreadNative.asInterface(b);
		String callingPackage = data.readString();
		Intent intent = Intent.CREATOR.createFromParcel(data);
		String resolvedType = data.readString();
		IBinder resultTo = data.readStrongBinder();
		String resultWho = data.readString();
		int requestCode = data.readInt();
		int startFlags = data.readInt();
		ProfilerInfo profilerInfo = data.readInt() != 0
		? ProfilerInfo.CREATOR.createFromParcel(data) : null;
		Bundle options = data.readInt() != 0
		? Bundle.CREATOR.createFromParcel(data) : null;
		int result = startActivity(app, callingPackage, intent, resolvedType,
		resultTo, resultWho, requestCode, startFlags, profilerInfo, options);
		reply.writeNoException();
		reply.writeInt(result);
		return true;
	}

	...
}
//startActivity方法
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
                               Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
                               int startFlags, ProfilerInfo profilerInfo, Bundle options){

	return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
	                           resultWho, requestCode, startFlags, profilerInfo, options,
	                           UserHandle.getCallingUserId());
}
//startActivityAsUser方法
@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
                                     Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
                                     int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId){
	enforceNotIsolatedCaller("startActivity");
	userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
	                            false, ALLOW_FULL_ONLY, "startActivity", null);
	// TODO: Switch to user app stacks here.
  //調用ActivityStackSupervisor的startActivityMayWait方法
	return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
	          resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
	          profilerInfo, null, null, options, userId, null, null);
}
ActivityStackSupervisor#startActivityMayWait
//startActivityMayWait
public void startActivityMayWait(){
   ...

  int res = startActivityLocked(caller, intent, resolvedType, aInfo,
                    voiceSession, voiceInteractor, resultTo, resultWho,
                    requestCode, callingPid, callingUid, callingPackage,
                    realCallingPid, realCallingUid, startFlags, options,
                    componentSpecified, null, container, inTask);
  ....
}
//startActivityLocked
public void startActivityLocked()
{
  ...
   resumeTopActivitiesLocked(targetStack, null, options);
   ...
}
//resumeTopActivitiesLocked
boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
                                  Bundle targetOptions)
{
	if (targetStack == null) {
		targetStack = getFocusedStack();
	}
	// Do targetStack first.
	boolean result = false;
	if (isFrontStack(targetStack)) {
    //resume 棧頂 Activity
		result = targetStack.resumeTopActivityLocked(target, targetOptions);
	}
	for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
		final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
		for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
			final ActivityStack stack = stacks.get(stackNdx);
			if (stack == targetStack) {
				// Already started above.
				continue;
			}
			if (isFrontStack(stack)) {
				stack.resumeTopActivityLocked(null);
			}
		}
	}
	return result;
}
ActivityStack#resumeTopActivityLocked
//resumeTopActivityLocked
final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options)
{
	if (mStackSupervisor.inResumeTopActivity) {
		// Don't even start recursing.
		return false;
	}

	boolean result = false;
	try {
		// Protect against recursion.
		mStackSupervisor.inResumeTopActivity = true;
		if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
			mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
			mService.updateSleepIfNeededLocked();
		}
		result = resumeTopActivityInnerLocked(prev, options);
	}
	finally {
		mStackSupervisor.inResumeTopActivity = false;
	}
	return result;
}
//resumeTopActivityInnerLocked
public void resumeTopActivityInnerLocked(){
  ....
  //調用startSpecificActivityLocked  這裏進行熱啓動 冷啓動的區分調用了
  mStackSupervisor.startSpecificActivityLocked(next, true, true);
  ...
}

//startSpecificActivityLocked 這裏進行熱啓動 冷啓動的區分調用了進入AMS的調用進程開啓新的App下半段了
void startSpecificActivityLocked(ActivityRecord r,
                                 boolean andResume, boolean checkConfig)
{
	// Is this activity's application already running?
	ProcessRecord app = mService.getProcessRecordLocked(r.processName,
	                    r.info.applicationInfo.uid, true);

	r.task.stack.setLaunchTime(r);

	if (app != null && app.thread != null) {
		try {
			if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
			          || !"android".equals(r.info.packageName)) {
				// Don't add this if it is a platform component that is marked
				// to run in multiple processes, because this is actually
				// part of the framework so doesn't make sense to track as a
				// separate apk in the process.
				app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
				               mService.mProcessStats);
			}
			realStartActivityLocked(r, app, 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.
	}

	mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
	                            "activity", r.intent.getComponent(), false, false, true);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章