美文网首页Android进阶之路Android开发我爱编程
Android源码阅读,Activity的启动流程分析

Android源码阅读,Activity的启动流程分析

作者: 刘付文 | 来源:发表于2018-04-13 17:32 被阅读133次
    一、首先从Activity的startActivity(Intent intent)方法开始分析
    @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }
    
    1.startActivity(Intent intent)其实调的是startActivity(Intent intent, @Nullable Bundle options),Bundle 是用于传递数据的。
    2.接着调用startActivityForResult(@RequiresPermission Intent intent, int requestCode,@Nullable Bundle options)这个方法。
    
    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
                @Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar =
                //  调的是Instrumentation的execStartActivity方法
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);   
        } 
    }
    

    1.startActivityForResult里面是去调用Instrumentation的execStartActivity()方法。

    二、来到Instrumentation类里面execStartActivity()方法
    // Instrumentation类里面的方法
    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        
        try {
            // ActivityManager.getService()其实就是ActivityManagerService
            int result = ActivityManager.getService()
                .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) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }
    

    1.execStartActivity()里面是去调用ActivityManagerService的startActivity()方法。

    三、来到ActivityManagerService类里面startActivity()方法
    1. startActivity() -->> startActivityAsUser()-->然后到ActivityStarter类的startActivityMayWait()
    @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) {
        // 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");
    }
    
    1. ActivityManagerService里面的startActivity(),最终会去调用ActivityStarter的startActivityMayWait()方法。
    四、来到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) {
            // 只留关键代码
            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;
        }
    }
    
    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;
    }
    
    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;
        // 1.中间这里做一系统的错误校验,如果有错误就返回Err
        if (err != START_SUCCESS) {
            if (resultRecord != null) {
                resultStack.sendActivityResultLocked(
                        -1, resultRecord, resultWho, requestCode, RESULT_CANCELED, null);
            }
            ActivityOptions.abort(options);
            return err;
        }
        // 2.对权限进行检查
        if (mService.mPermissionReviewRequired && aInfo != null) {
            if (mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
                    aInfo.packageName, userId)) {
                IIntentSender target = mService.getIntentSenderLocked(
                        ActivityManager.INTENT_SENDER_ACTIVITY, callingPackage,
                        callingUid, userId, null, null, 0, new Intent[]{intent},
                        new String[]{resolvedType}, PendingIntent.FLAG_CANCEL_CURRENT
                                | PendingIntent.FLAG_ONE_SHOT, null);
    
                final int flags = intent.getFlags();
                Intent newIntent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
                newIntent.setFlags(flags
                        | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                newIntent.putExtra(Intent.EXTRA_PACKAGE_NAME, aInfo.packageName);
                newIntent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
                if (resultRecord != null) {
                    newIntent.putExtra(Intent.EXTRA_RESULT_NEEDED, true);
                }
                intent = newIntent;
    
                resolvedType = null;
                callingUid = realCallingUid;
                callingPid = realCallingPid;
    
                rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId);
                aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags,
                        null /*profilerInfo*/);
    
                if (DEBUG_PERMISSIONS_REVIEW) {
                    Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true,
                            true, false) + "} from uid " + callingUid + " on display "
                            + (container == null ? (mSupervisor.mFocusedStack == null ?
                            DEFAULT_DISPLAY : mSupervisor.mFocusedStack.mDisplayId) :
                            (container.mActivityDisplay == null ? DEFAULT_DISPLAY :
                                    container.mActivityDisplay.mDisplayId)));
                }
            }
        }
        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();
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity);
        } finally {
         
        }
        return result;
    }
    
    // 只有调用了startActivity才会来到这个方法
    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
    
        // 检查是否应该只启动一次。猜是和启动模式有关
        final ActivityStack topStack = mSupervisor.mFocusedStack;
        final ActivityRecord topFocused = topStack.topActivity();
        final ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(mNotTop);
        final boolean dontStart = top != null && mStartActivity.resultTo == null
                && top.realActivity.equals(mStartActivity.realActivity)
                && top.userId == mStartActivity.userId
                && top.app != null && top.app.thread != null
                && ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
                || mLaunchSingleTop || mLaunchSingleTask);
        if (dontStart) {
            ActivityStack.logStartActivity(AM_NEW_INTENT, top, top.getTask());
            // 确保只启动一次的Activity处理Resume状态.
            topStack.mLastPausedActivity = null;
            if (mDoResume) {
                // 关键方法
                mSupervisor.resumeFocusedStackTopActivityLocked();
            }
            ActivityOptions.abort(mOptions);
            if ((mStartFlags & 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!
                return START_RETURN_INTENT_TO_CALLER;
            }
      
            return START_DELIVERED_TO_TOP;
        }
        
        // 新的任务
        boolean newTask = false;
        final TaskRecord taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
                ? mSourceRecord.getTask() : null;
    
        // Should this be considered a new task?
        int result = START_SUCCESS;
        
        if (newTask) {
            EventLog.writeEvent(
                    EventLogTags.AM_CREATE_TASK, mStartActivity.userId,
                    mStartActivity.getTask().taskId);
        }
    
        mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
                mOptions);
        if (mDoResume) {
            final ActivityRecord topTaskActivity =
                    mStartActivity.getTask().topRunningActivityLocked();
            if (!mTargetStack.isFocusable()
                    || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                    && mStartActivity != topTaskActivity)) {
       
            } else {
                // 关键方法
                mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                        mOptions);
            }
        } 
        return START_SUCCESS;
    }
    
    1. startActivityMayWait方法,里面是去调用startActivityLocked方法
    2. startActivityLocked方法,里面是去调用startActivity方法
    3. 在startActivity方法里,做一些错误的校验和权限的校验,然后调用startActivityUnchecked方法
    4. startActivityUnchecked方法,最终会去调用ActivityStackSupervisor类里面的resumeFocusedStackTopActivityLocked方法。
    五、来到ActivityStackSupervisor类里面resumeFocusedStackTopActivityLocked()方法
    boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
        if (targetStack != null && isFocusedStack(targetStack)) {
            // 调用ActivityStack类里面的方法
            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
        return false;
    }
    
    六、来到ActivityStack 类里面resumeTopActivityUncheckedLocked()方法
    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        try {
            mStackSupervisor.inResumeTopActivity = true;
            result = resumeTopActivityInnerLocked(prev, options);
        } finally {
            mStackSupervisor.inResumeTopActivity = false;
        }
        return result;
    }
    
    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        // 判断上个Activity有没有onPause
       boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
        if (mResumedActivity != null) {
           // startPausingLocked这个方法,就是去调用Activity的onPause生命周期
            pausing |= startPausingLocked(userLeaving, false, next, false);
        }
      // 前面删掉了一系统的判断方法
       if (next.app != null && next.app.thread != null) {
           
        } else {
            // 启动Activity关键方法
            mStackSupervisor.startSpecificActivityLocked(next, true, true);
        }
    
        return true;
    }
    
    1. resumeTopActivityUncheckedLocked()方法,去调用resumeTopActivityInnerLocked()这个方法
    2. resumeTopActivityInnerLocked()方法,去调用ActivityStackSupervisor类的startSpecificActivityLocked()这个方法
    3. 在这里可以看到,其实Activity的启动,先去调用当前Activity的onPause方法后,再去执行要启动Activity。
    七、回到到ActivityStackSupervisor类里面startSpecificActivityLocked()方法
    void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {  
        if (app != null && app.thread != null) {
            try {               
                // 真正去启动Activity了
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }
    
        }
    }
    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
     
        try {
            // 千辛万苦终于到这里了
            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);
    
        } catch (RemoteException e) {
           
        }
    
        return true;
    }
    
    1. 最终会去调用ApplicationThread里面的scheduleLaunchActivity方法,ApplicationThread这个类在ActivityThread里面。
    2. 其实前面一系列方法都只是前戏,Activity创建和生命周期的回调等等这些关键的方法,都在ActivityThread这个类里面,下面就去看ActivityThread这个类。
    七、来到ApplicationThread类里面scheduleLaunchActivity()方法,从这里开始是重点看的地方
    @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 void sendMessage(int what, Object obj) {
        sendMessage(what, obj, 0, 0, false);
    }
    
    private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        // 最终通过mH发送消息
        mH.sendMessage(msg);
    }
    
    public void handleMessage(Message msg) {
            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;
            }
    }
    
    1. scheduleLaunchActivity方法是将启动的Activity信息进行封装,然后通过mH发送出去。
    2. 在mH的handleMessage方法,通过msg.wha找到最终执行的方法。
    3. 最终执行handleLaunchActivity()方法。
    八、来到ActivityThread类里面handleLaunchActivity()方法
    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
       
        // 创建Activity的关键方法
        Activity a = performLaunchActivity(r, customIntent);
    
        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            reportSizeConfigurations(r);
            Bundle oldState = r.state;
            // 这个方法最终会去判断要不要执行onRestart 和执行onStart和onResume方法,自已去看了
            // View的绘制也是在这里开始的。
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
    
         
        } 
    }
    1. performLaunchActivity方法分析
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            // 1. 创建 Activity ,在Instrumentation类的newActivity()方法里面
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
        } catch (Exception e) {
           
        }
    
        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            if (activity != null) {
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                // 1.1 第一个是执行Activity的attach方法
                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 (r.isPersistable()) {
                    // 2. Instrumentation类的方法,其实最后就是调用Activity里面的onCreate
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                
            }
            r.paused = true;
        } 
    
        return activity;
    }
    
    // 1. Instrumentation类创建Activity的方法
    public Activity newActivity(ClassLoader cl, String className,
            Intent intent)
            throws InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        return (Activity)cl.loadClass(className).newInstance();
    }
    
    // 2. Instrumentation类的callActivityOnCreate方法
    public void callActivityOnCreate(Activity activity, Bundle icicle,
        PersistableBundle persistentState) {
        prePerformCreate(activity);
        // 调用Activity的performCreate方法
        activity.performCreate(icicle, persistentState);
        postPerformCreate(activity);
    }
    
    // 3. Activity类的方法
    final void performCreate(Bundle icicle) {
        restoreHasCurrentPermissionRequest(icicle);
        // 执行onCreate生命周期回调
        onCreate(icicle);
        mActivityTransitionState.readState(icicle);
        performCreateCommon();
    }
    
      // 这方法
    final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
        ActivityClientRecord r = mActivities.get(token);
    
        // 这方法里面最终会判断去调用onReStart onStart  onResume生命周期
        r = performResumeActivity(token, clearHide, reason);
    
        if (r != null) {
            final Activity a = r.activity;
        
            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;
                        // 我们的View是添加在ViewManager--》WindowManager--》WindowManagerImpl(这个实现类)
                        // View 的绘制流程是从这里开始的
                        wm.addView(decor, l);
                    } 
                } 
            }
    
            
    
        } 
    }
    
    1. Activity的创建,是ClassLoader这个类通过Activity的名称调用 自已的loadClass(className)方法,找到Activity的Class类,然后通过Class类反射创建Activity。
    2. Activity创建后,会调用自己的 attach() -- >> onCreate() -->> onStart() -->onResume()生命周期的方法。
    3. 在调用Activity的onResume方法后,开始调用WindowManagerImpl类的addView方法,开始执行View的绘制流程。
    4. Activity的启动到此就差不多结束,我只是挑了一些关键的代码,其它的还是要自己打开源码多看几遍。

    别人写得更好,可以继续看:
    【凯子哥带你学Framework】Activity启动过程全解析
    Android 7.1.2(Android N) Activity启动流程分析
    Android系统源码分析--Activity启动过程

    相关文章

      网友评论

        本文标题:Android源码阅读,Activity的启动流程分析

        本文链接:https://www.haomeiwen.com/subject/bnbckftx.html