从 startActivity 看activity启动流程

没有从 系统启动流程分析,只是通过应用启动简单的分析一下。
启动一个activity 一般是通过本activity 直接调用 startActivity方法开启。
首先调用

@Override
public void startActivity(Intent intent) {
    //调用这个方法其实到最后会调用到 startActivityForResult(Intent intent, int requestCode, Bundle options);
    startActivity(intent , null) ;
}

@Override
public void startActivity(Intent intent 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) ;
    }
}

public void startActivityForResult(Intent intent , int requestCode Bundle options) {
    //这里判断之后执行的方法是一样的,只是传入的activity不一样
    if (mParent ==  null) {
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                    //第三个参数
                this, mMainThread.getApplicationThread() mToken , this,
                intent requestCode options) ;
        if (ar !=  null) {  //这里是由上面检测出来发现结果需要返回,就会执行下一个方法
            mMainThread.sendActivityResult(
                mToken mEmbeddedID requestCode ar.getResultCode() ,
                ar.getResultData()) ;
        }
        if (requestCode >=  0) {
            // If this start is requesting a result, we can avoid making
            // the activity visible until the result is received.  Setting
            // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
            // activity hidden during this time, to avoid flickering.
            // This can only be done when a result is requested because
            // that guarantees we will get information back when the
            // activity is finished, no matter what happens to it.
            mStartedActivity =  true;
        }
    }  else {
        if (options !=  null) {
            mParent.startActivityFromChild( this, intent requestCode options) ;
       else {
            // Note we want to go through this method for compatibility with
            // existing applications that may have overridden it.
            mParent.startActivityFromChild( this, intent requestCode) ;
        }
    }
}


public void  startActivityFromChild(Activity child Intent intent
        int requestCode Bundle options) {
    Instrumentation.ActivityResult ar =
        mInstrumentation.execStartActivity(
            this, mMainThread.getApplicationThread() mToken child ,
            intent requestCode options) ;
    if (ar !=  null) {
        mMainThread.sendActivityResult(
            mToken child.mEmbeddedID requestCode ,
            ar.getResultCode() ar.getResultData()) ;
    }
}


public ActivityResult execStartActivity(
        Context who IBinder contextThread IBinder token Activity 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) ;
                if (am.match(who , null, intent)) {
                    am.mHits++ ;
                    if (am.isBlocking()) {  //这里检测是不是需要结果返回
                        return requestCode >=  ? am.getResult() :  null;
                    }
                    break;
                }
            }
        }
    }
    try {
        intent.setAllowFds( false) ;
        intent.migrateExtraStreamToClipData() ;
        int result = ActivityManagerNative.getDefault()
            .startActivity(whoThread intent ,
                    intent.resolveTypeIfNeeded(who.getContentResolver()) ,
                    token target !=  null ? target.mEmbeddedID :  null,
                    requestCode 0 , null, null, options) ;
        checkStartActivityResult(result intent) ;
   catch (RemoteException e) {
    }
    return null;
}

上面的逻辑是先去检测是不是请求的需要结果返回,是的话就跳出循环执行activity中的这个方法,这里还是暂且不看后面会有提到 接着向下看

if (ar !=  null) {  //这里是由上面检测出来发现结果需要返回,就会执行下一个方法
    mMainThread.sendActivityResult(
            mToken mEmbeddedID requestCode ar.getResultCode() ,
            ar.getResultData()) ;
}
if (requestCode >=  0) {
    mStartedActivity =  true;
}


try {
    intent.setAllowFds( false) ;
    intent.migrateExtraStreamToClipData() ;
    int result = ActivityManagerNative.getDefault()
        .startActivity(whoThread intent ,
                intent.resolveTypeIfNeeded(who.getContentResolver()) ,
                token target !=  null ? target.mEmbeddedID :  null,
                requestCode 0 , null, null, options) ;

      //这里检测activity开启的各种异常
    checkStartActivityResult(result intent) ;
catch (RemoteException e) {
}

//这里是不是很熟悉呀 
/*package*/  static void checkStartActivityResult( int res Object intent) {
    if (res >= ActivityManager.START_SUCCESS) {
        return;
    }
   
    switch (res) {
        case ActivityManager.START_INTENT_NOT_RESOLVED:
        case ActivityManager.START_CLASS_NOT_FOUND:
            if (intent  instanceof Intent && ((Intent)intent).getComponent() !=  null)
                throw new ActivityNotFoundException(
                        "Unable to find explicit activity class "
                        + ((Intent)intent).getComponent().toShortString()
                        +  "; have you declared this activity in your AndroidManifest.xml?") ;
            throw new ActivityNotFoundException(
                    "No Activity found to handle " + intent) ;
        case ActivityManager.START_PERMISSION_DENIED:
            throw new SecurityException( "Not allowed to start activity "
                    + intent) ;
        case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
            throw new AndroidRuntimeException(
                    "FORWARD_RESULT_FLAG used while also requesting a result") ;
        case ActivityManager.START_NOT_ACTIVITY:
            throw new IllegalArgumentException(
                    "PendingIntent is not an activity") ;
        default:
            throw new AndroidRuntimeException( "Unknown error code "
                    + res +  " when starting " + intent) ;
    }
}


private static final Singleton<IActivityManager> gDefault =  new Singleton<IActivityManager>() {
    protected IActivityManager create() {
        IBinder b = ServiceManager.getService( "activity") //这里得到activity管理器通过ServiceManager去拿
        if ( false) {
            Log.v( "ActivityManager" "default service binder = " + b) ;
        }
        //这里是有的管理器 都是实现了抽象类ActivityManagerNative 这里要说到的也是他的子类之一ActivityManagerService
        //对象实现具体操作
        IActivityManager am = asInterface(b) ;
        if ( false) {
            Log.v( "ActivityManager" "default service = " + am) ;
        }
        return am ;
    }
} ;

/**
 * Cast a Binder object into an activity manager interface, generating
 * a proxy if needed.
 */
static public IActivityManager asInterface(IBinder obj) {
    if (obj ==  null) {
        return null;
    }
    IActivityManager in =
        (IActivityManager)obj.queryLocalInterface(descriptor) ;
    if (in !=  null) {
        return in ;
    }

    return new ActivityManagerProxy(obj) ;
}

 
public int startActivity(IApplicationThread caller, Intent intent,
String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, String profileFile,
ParcelFileDescriptor profileFd, Bundle options) throws RemoteException {
    Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
data.writeStrongBinder(caller != null ? caller.asBinder() : null);
intent.writeToParcel(data, 0);
data.writeString(resolvedType);
data.writeStrongBinder(resultTo);
data.writeString(resultWho);
data.writeInt(requestCode);
data.writeInt(startFlags);
data.writeString(profileFile);
    if (profileFd != null) {
        data.writeInt(1);
profileFd.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 方法来完成开启
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
reply.readException();
    int result = reply.readInt();
reply.recycle();
data.recycle();
    return result;
}

                                                                        

public final boolean transact( int code Parcel data Parcel reply ,
        int flags)  throws RemoteException {
    if ( false) Log.v( "Binder" "Transact: " + code +  " to " this) ;
    if (data !=  null) {
        data.setDataPosition( 0) ;
    }
    //这里其实是通过调用 onTransact 完成操作
    boolean r = onTransact(code data reply flags) ;
    if (reply !=  null) {
        reply.setDataPosition( 0) ;
    }
    return r ;
}

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) ;
        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() ;
        String profileFile = data.readString() ;
        ParcelFileDescriptor profileFd = data.readInt() !=  0
                ? data.readFileDescriptor() :  null;
        Bundle options = data.readInt() !=  0
                ? Bundle.CREATOR.createFromParcel(data) :  null;
        //这里还是调用了startActivity方法实现的 其实就是 ActivityManagerNative 的 startActivity 方法
        int result = startActivity(app intent resolvedType ,
                resultTo resultWho requestCode startFlags ,
                profileFile profileFd options) ;
        reply.writeNoException() ;
        reply.writeInt(result) ;
        return true;
    }

public final int startActivity(IApplicationThread caller ,
        Intent intent String resolvedType IBinder resultTo ,
        String resultWho , int requestCode , int startFlags ,
        String profileFile ParcelFileDescriptor profileFd Bundle options) {
    enforceNotIsolatedCaller( "startActivity") ;
    int userId =  0 ;
    if (intent.getCategories() !=  null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
        // Requesting home, set the identity to the current user
        // HACK!
        userId = mCurrentUserId ;
   else {
        // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
        // the current user's userId
        if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
            userId =  0 ;
       else {
            userId = Binder.getOrigCallingUser() ;
        }
    }
    //这里其实 是由 ActivityStack 类来执行的操作
    return mMainStack.startActivityMayWait(caller - 1 intent resolvedType ,
            resultTo resultWho requestCode startFlags profileFile profileFd ,
            null, null, options userId) ;
}


final int startActivityMayWait(IApplicationThread caller , int callingUid ,
        Intent intent String resolvedType IBinder resultTo ,
        String resultWho , int requestCode , int startFlags String profileFile ,
        ParcelFileDescriptor profileFd WaitResult outResult Configuration config ,
        Bundle options , int userId) {
    // Refuse possible leaked file descriptors
    if (intent !=  null && intent.hasFileDescriptors()) {
        throw new IllegalArgumentException( "File descriptors passed in Intent") ;
    }
    boolean componentSpecified = intent.getComponent() !=  null;

    // Don't modify the client's object!
    intent =  new Intent(intent) ;

    // Collect information about the target of the Intent.
    //去找对应的activity信息
    ActivityInfo aInfo = resolveActivity(intent resolvedType startFlags ,
            profileFile profileFd userId) ;
    if (aInfo !=  null && mService.isSingleton(aInfo.processName aInfo.applicationInfo)) {
        userId =  0 ;
    }

    //将应用信息放里面
    aInfo = mService.getActivityInfoForUser(aInfo userId) ;
//执行这个方法
int res = startActivityLocked(caller intent resolvedType ,
        aInfo resultTo resultWho requestCode callingPid callingUid ,
        startFlags options componentSpecified , null) ;

final int startActivityLocked(IApplicationThread caller ,
        Intent intent String resolvedType ActivityInfo aInfo IBinder resultTo ,
        String resultWho , int requestCode ,
        int callingPid , int callingUid , int startFlags Bundle options ,
        boolean componentSpecified ActivityRecord[] outActivity) {

    //准备进行activity信息检查
    int err = ActivityManager.START_SUCCESS ;

    //进程信息
    ProcessRecord callerApp =  null;
    if (caller !=  null) {
        callerApp = mService.getRecordForAppLocked(caller) ;
        if (callerApp !=  null) {
            callingPid = callerApp.pid ;
            callingUid = callerApp.info.uid ;
       else {
            Slog.w(TAG "Unable to find app for caller " + caller
                  +  " (pid=" + callingPid +  ") when starting: "
                  + intent.toString()) ;
            err = ActivityManager.START_PERMISSION_DENIED ;
        }
    }

ActivityRecord sourceRecord =  null;  //应用的配置的启动的Activity的ActivityRecord。
ActivityRecord resultRecord =  null;
if (resultTo !=  null) {
    int index = indexOfTokenLocked(resultTo) ;
    if (DEBUG_RESULTS) Slog.v(
        TAG "Will send result to " + resultTo +  " (index " + index +  ")") ;
    if (index >=  0) {
        sourceRecord = mHistory.get(index) ;
        if (requestCode >=  && !sourceRecord.finishing) {  //还没看明白
            resultRecord = sourceRecord ;
        }
    }
}


final int startAnyPerm = mService.checkPermission(
        START_ANY_ACTIVITY callingPid callingUid) ;
final int componentPerm = mService.checkComponentPermission(aInfo.permission callingPid ,
        callingUid aInfo.applicationInfo.uid aInfo.exported) ;
if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {  //不是允许 就发送一个取消操作
    if (resultRecord !=  null) {  //执行一个无效操作
        sendActivityResultLocked(- 1 ,
            resultRecord resultWho requestCode ,
            Activity.RESULT_CANCELED , null) ;
    }


if (mMainStack) {
    if (mService.mController !=  null) {
        boolean abort =  false;
        try {
            // The Intent we give to the watcher has the extra data
            // stripped off, since it can contain private information.
            Intent watchIntent = intent.cloneFilter() //这里可能是检测到开启,之后 返回false 然后下面用开启成功标志,其实做的是取消操作
            abort = !mService.mController.activityStarting(watchIntent ,
                    aInfo.applicationInfo.packageName) ;
       catch (RemoteException e) {
            mService.mController =  null;
        }


  //生成一个activity记录,在栈中代表一个activity
// An ActivityRecord in the history stack, representing an activity.
 ActivityRecord r =  new ActivityRecord(ce ,湛zhongz  this, callerApp callingUid ,
         intent resolvedType aInfo mService.mConfiguration ,
         resultRecord resultWho requestCode componentSpecified) ;


//继续调用相关方法
err = startActivityUncheckedLocked(r sourceRecord ,
        startFlags , true, options) ;

调用相关方法是在上 startActivityLocked方法结尾处调用

final int startActivityUncheckedLocked(ActivityRecord r ,
        ActivityRecord sourceRecord , int startFlags , boolean doResume ,
        Bundle options) {
    final Intent intent = r.intent ;
    final int callingUid = r.launchedFromUid ;
    final int userId = r.userId ;

    int launchFlags = intent.getFlags() ;
   
    // We'll invoke onUserLeaving before onPause only if the launching
    // activity did not explicitly state that this is an automated launch.
    //在onPause()之前会调用onUserLeaving( )方法,如果使用了该标识,说明目标Activity不和用户交互,所以也就不需要回调onUserLeaving()方法。
    mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) ==  0 ;
    if (DEBUG_USER_LEAVING) Slog.v(TAG ,
            "startActivity() => mUserLeaving=" + mUserLeaving) ;
   
    // If the caller has asked not to resume at this point, we make note
    // of this in the record so that we can skip it when trying to find
    // the top running activity.
    if (!doResume) {  //在这个点不要求resume,记录下来跳过
        r.delayedResume =  true;
    }

    //这个是将上一个activity置为栈顶,而不是新开启的那一个。
    ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
            !=  ? r :  null;

// current top activity as the caller.
//如果有这个activity实例,将共用一个,否则 调用起来一个新的
if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) !=  0) {
    ActivityRecord checkedCaller = sourceRecord ;
    if (checkedCaller ==  null) {
        checkedCaller = topRunningNonDelayedActivityLocked(notTop) ;
    }
    if (!checkedCaller.realActivity.equals(r.realActivity)) {
        // Caller is not the same as launcher, so always needed.
        startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED ;
    }
}

//这几种情况下都需要一个新的栈启动
if (sourceRecord ==  null) {
    // This activity is not being started from another...  in this
    // case we -always- start a new task.
    //没有被开启过 就开启一个新的栈
    if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) ==  0) {
        Slog.w(TAG "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
              + intent) ;
        launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK ;
else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
    // The original activity who is starting us is running as a single
    // instance...  this new activity it is starting must go on its
    // own task.
    launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK ;
else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
        || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
    // The activity being started is a single instance...  it always
    // gets launched into its own task.
    launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK ;
}


//在某种情况下启动了一个新的栈,立刻调用返回,让这个启动能够正常的进行下去
if (r.resultTo !=  null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) !=  0) {
    // For whatever reason this activity is being launched into a new
    // task...  yet the caller has requested a result back.  Well, that
    // is pretty messed up, so instead immediately send back a cancel
    // and let the new task continue launched as normal without a
    // dependency on its originator.
    Slog.w(TAG "Activity is launching as a new task, so cancelling activity result.") ;
    sendActivityResultLocked(- 1 ,
            r.resultTo r.resultWho r.requestCode ,
        Activity.RESULT_CANCELED , null) ;
    r.resultTo =  null;
}

boolean addingToTask =  false;
boolean movedHome =  false;
TaskRecord reuseTask =  null;

下面都是对这个进行判断说明


boolean addingToTask =  false;
boolean movedHome =  false;
TaskRecord reuseTask =  null;
//如果里面已经有了这个相同的东西,就把这个东西拿来用,而不是创建一个新的。
if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) !=  &&
        (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) ==  0)
        || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
        || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
    // If bring to front is requested, and no result is requested, and
    // we can find a task that was started with this same
    // component, then instead of launching bring that one to the front.
    if (r.resultTo ==  null) {
        // See if there is a task to bring to the front.  If this is
        // a SINGLE_INSTANCE activity, there can be one and only one
        // instance of it in the history, and it is always in its own
        // unique task, so we do a special search.
        ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
                ? findTaskLocked(intent r.info)
                : findActivityLocked(intent r.info) ;
        if (taskTop !=  null) {
            if (taskTop.task.intent ==  null) {
                // This task was started because of movement of
                // the activity based on affinity...  now that we
                // are actually launching it, we can assign the
                // base intent.
                taskTop.task.setIntent(intent r.info) ;
            }
            // If the target task is not in the front, then we need
            // to bring it to the front...  except...  well, with
            // SINGLE_TASK_LAUNCH it's not entirely clear.  We'd like
            // to have the same behavior as if a new instance was
            // being started, which means not bringing it to the front
            // if the caller is not itself in the front.
            ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop) ;
            if (curTop !=  null && curTop.task != taskTop.task) {
                r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) ;
                boolean callerAtFront = sourceRecord ==  null
                        || curTop.task == sourceRecord.task ;
                if (callerAtFront) {
                    // We really do want to push this one into the
                    // user's face, right now.
                    movedHome =  true;
                    moveHomeToFrontFromLaunchLocked(launchFlags) ;
                    moveTaskToFrontLocked(taskTop.task r options) ;
                    options =  null;
                }
            }
            // If the caller has requested that the target task be
            // reset, then do so.
            if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) !=  0) {
                taskTop = resetTaskIfNeededLocked(taskTop r) ;
            }
            if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED)  !=  0) {
                // We don't need to start a new activity, and
                // the client said not to do anything if that
                // is the case, so this is it!  And for paranoia, make
                // sure we have correctly resumed the top activity.
                if (doResume) {
                    resumeTopActivityLocked( null, options) ;
               else {
                    ActivityOptions.abort(options) ;
                }
                return ActivityManager.START_RETURN_INTENT_TO_CALLER ;
            }
            if ((launchFlags &
                    (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
                    == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
                // The caller has requested to completely replace any
                // existing task with its new activity.  Well that should
                // not be too hard...
                reuseTask = taskTop.task ;
                performClearTaskLocked(taskTop.task.taskId) ;
                reuseTask.setIntent(r.intent r.info) ;
           else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) !=  0
                    || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
                    || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
                // In this situation we want to remove all activities
                // from the task up to the one being started.  In most
                // cases this means we are resetting the task to its
                // initial state.
                ActivityRecord top = performClearTaskLocked(
                        taskTop.task.taskId r launchFlags) ;
                if (top !=  null) {
                    if (top.frontOfTask) {
                        // Activity aliases may mean we use different
                        // intents for the top activity, so make sure
                        // the task now has the identity of the new
                        // intent.
                        top.task.setIntent(r.intent r.info) ;
                    }
                    logStartActivity(EventLogTags.AM_NEW_INTENT r top.task) ;
                    top.deliverNewIntentLocked(callingUid r.intent) ;
               else {
                    // A special case: we need to
                    // start the activity because it is not currently
                    // running, and the caller has asked to clear the
                    // current task to have this activity at the top.
                    addingToTask =  true;
                    // Now pretend like this activity is being started
                    // by the top of its task, so it is put in the
                    // right place.
                    sourceRecord = taskTop ;
                }
            }  else if (r.realActivity.equals(taskTop.task.realActivity)) {
                // In this case the top activity on the task is the
                // same as the one being launched, so we take that
                // as a request to bring the task to the foreground.
                // If the top activity in the task is the root
                // activity, deliver this new intent to it if it
                // desires.
                if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) !=  0
                        && taskTop.realActivity.equals(r.realActivity)) {
                    logStartActivity(EventLogTags.AM_NEW_INTENT r taskTop.task) ;
                    if (taskTop.frontOfTask) {
                        taskTop.task.setIntent(r.intent r.info) ;
                    }
                    taskTop.deliverNewIntentLocked(callingUid r.intent) ;
               else if (!r.intent.filterEquals(taskTop.task.intent)) {
                    // In this case we are launching the root activity
                    // of the task, but with a different intent.  We
                    // should start a new instance on top.
                    addingToTask =  true;
                    sourceRecord = taskTop ;
                }
            }  else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) ==  0) {
                // In this case an activity is being launched in to an
                // existing task, without resetting that task.  This
                // is typically the situation of launching an activity
                // from a notification or shortcut.  We want to place
                // the new activity on top of the current task.
                addingToTask =  true;
                sourceRecord = taskTop ;
           else if (!taskTop.task.rootWasReset) {
                // In this case we are launching in to an existing task
                // that has not yet been started from its front door.
                // The current task has been brought to the front.
                // Ideally, we'd probably like to place this new task
                // at the bottom of its stack, but that's a little hard
                // to do with the current organization of the code so
                // for now we'll just drop it.
                taskTop.task.setIntent(r.intent r.info) ;
            }
            if (!addingToTask && reuseTask ==  null) {
                // We didn't do anything...  but it was needed (a.k.a., client
                // don't use that intent!)  And for paranoia, make
                // sure we have correctly resumed the top activity.
                if (doResume) {
                    resumeTopActivityLocked( null, options) ;
               else {
                    ActivityOptions.abort(options) ;
                }
                return ActivityManager.START_TASK_TO_FRONT ;
            }
        }
    }


    logStartActivity(EventLogTags.AM_CREATE_ACTIVITY r r.task) ;
    startActivityLocked(r newTask doResume keepCurTransition options) ;
    return ActivityManager.START_SUCCESS ;
最后会调用 startActivityLocked方法

private final void startActivityLocked(ActivityRecord r , boolean newTask ,
        boolean doResume , boolean keepCurTransition Bundle options) {
    //NH描述的是将参数r描述的是正在启动的Activity组件保存在Activity组件堆栈前系统已经启动了的Activity组件的个数
    final int NH = mHistory.size() ;

    int addPos = - 1 ;
   
    if (!newTask) {
        // If starting in an existing task, find where that is...
        boolean startIt =  true;
        for ( int i = NH- 1 i >=  0 i--) {
            ActivityRecord p = mHistory.get(i) ;
            if (p.finishing) {
                continue;
            }
            if (p.task == r.task) {  //将对应的activity添加到相应的位置
                // Here it is!  Now, if this is not yet visible to the
                // user, then just add it without starting; it will
                // get started when the user navigates back to it.
                addPos = i+ 1 ;
                if (!startIt) {
                    if (DEBUG_ADD_REMOVE) {
                        RuntimeException here =  new RuntimeException( "here") ;
                        here.fillInStackTrace() ;
                        Slog.i(TAG "Adding activity " + r +  " to stack at " + addPos ,
                                here) ;
                    }
                    mHistory.add(addPos r) ;
                    r.putInHistory() ;
                    mService.mWindowManager.addAppToken(addPos r.appToken r.task.taskId ,
                            r.info.screenOrientation r.fullscreen) ;
                    if (VALIDATE_TOKENS) {
                        validateAppTokensLocked() ;
                    }
                    ActivityOptions.abort(options) ;
                    return;
                }
                break;
            }
            if (p.fullscreen) {
                startIt =  false;
            }
        }
    }

    // Place a new activity at top of stack, so it is next to interact
    // with the user.
    if (addPos <  0) {
        addPos = NH ;
    }
   

//这里是做activity之类的组件操作
if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) !=  0) {
    mService.mWindowManager.prepareAppTransition(
            WindowManagerPolicy.TRANSIT_NONE keepCurTransition) ;
    mNoAnimActivities.add(r) ;
else {
    mService.mWindowManager.prepareAppTransition(newTask
            ? WindowManagerPolicy.TRANSIT_TASK_OPEN
            : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN keepCurTransition) ;
    mNoAnimActivities.remove(r) ;
}


if (doResume) {  //这里接着执行这个方法 将activity显示
    resumeTopActivityLocked( null) ;
}

resumeTopAcivityLocked  会对activity有没有进行初始化 和构造进行判断 最后会调用ActivityThread 来显示activity 接着向下看  resumeTopAcivityLocked 在开启activity时 调用  startSpecificActivityLocked(next,true,true),

if (app !=  null && app.thread !=  null) {
    try {
        app.addPackage(r.info.packageName) ;
        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.
}

在realStartActivityLocaked中 
app.thread.scheduleLaunchActivity( new Intent(r.intent) r.appToken ,
        System.identityHashCode(r) r.info ,
        new Configuration(mService.mConfiguration) ,
        r.compat r.icicle results newIntents !andResume ,
        mService.isNextTransitionForward() profileFile profileFd ,
        profileAutoStop) ;


这个函数调用中的thread 其实是 ActivityThread 一个内部类 ApplicationThread

public final void scheduleLaunchActivity(Intent intent IBinder token , int ident ,
        ActivityInfo info Configuration curConfig CompatibilityInfo compatInfo ,
        Bundle state List<ResultInfo> pendingResults ,
        List<Intent> pendingNewIntents , boolean notResumed , boolean isForward ,
        String profileName ParcelFileDescriptor profileFd , boolean autoStopProfiler) {
    ActivityClientRecord r =  new ActivityClientRecord() ;

    r.token = token ;
    r.ident = ident ;
    r.intent = intent ;
    r.activityInfo = info ;
    r.compatInfo = compatInfo ;
    r.state = state ;

    r.pendingResults = pendingResults ;
    r.pendingIntents = pendingNewIntents ;

    r.startsNotResumed = notResumed ;
    r.isForward = isForward ;

    r.profileFile = profileName ;
    r.profileFd = profileFd ;
    r.autoStopProfiler = autoStopProfiler ;

    updatePendingConfiguration(curConfig) ;

    queueOrSendMessage( H.LAUNCH_ACTIVITY r) ;
}

case LAUNCH_ACTIVITY: {
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER "activityStart") ;
    ActivityClientRecord r = (ActivityClientRecord)msg.obj ;

    r.packageInfo = getPackageInfoNoCheck(
            r.activityInfo.applicationInfo r.compatInfo) ;
    handleLaunchActivity(r , null) ;
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER) ;
break;


Activity a =  performLaunchActivity(r customIntent) ;

在handleLunchActivity这个方法中执行 performLunchActivity 对 activity进行构造和初始化。
Activity activity =  null;
try {
    //这里拿到类加载器,通过反射 将activity构造出来
    java.lang.ClassLoader cl = r.packageInfo.getClassLoader() ;
    //反射 狗仔activity 并对activity 进行初始化
    activity = mInstrumentation.newActivity(
            cl component.getClassName() r.intent) ;
    StrictMode.incrementExpectedActivityCount(activity.getClass()) ;
    r.intent.setExtrasClassLoader(cl) ;
    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) ;
    }
}

Instrumentation 类 
public Activity newActivity(Class<?> clazz Context context
        IBinder token Application application Intent intent ActivityInfo info
        CharSequence title Activity parent String id ,
        Object lastNonConfigurationInstance)  throws InstantiationException
        IllegalAccessException {
    Activity activity = (Activity)clazz.newInstance() ;
    ActivityThread aThread =  null;
    activity.attach(context aThread , this, token application intent ,
            info title parent id ,
            (Activity.NonConfigurationInstances)lastNonConfigurationInstance ,
            new Configuration()) ;
    return activity ;
}

构造,并调用 attach方法。

回到performLaunchActivity方法,在这个方法的结尾处,会调用 

mInstrumentation.callActivityOnCreate(activity r.state) ;


执行onCreate操作,现在回到 handleLunchActivity 方法中,在activity 实例化之后会执行
handleResumeActivity(r.token , false, r.isForward) //开始将构造出来的activity 展示出来

操作,具体ui展示会调用 

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) {
    a.mWindowAdded =  true;
    wm.addView(decor l) ;    //开始展示view
}

wm.addView 操作里面去展示和绘制ui,具体流程比较复杂,不在这里说明。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值