android四大组件之一-activity实现原理分析(已废弃)

前言:

这篇文章是很早期的文章,写的并不好,建议看下面这篇:

android四大组件之一-Activity实现原理分析_失落夏天的博客-CSDN博客



内容主体:


整理下,这样写还是不太好的。
先总体分为几个流程,activity,Instrumentation,ActivityManagerService,ActivityStarter,ActivityThread这几大部分。
其中activity,Instrumentation,ActivityThread属于用户进程,其余的属于系统进程。
 

一Activity中的启动
在activity中,无论何种方式调用startActivity,最终都会调用到
startActivityForResult();方法

二Instrumentation部分最终调用方法:
int result = ActivityManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);其中whoThread是当前用户进程的ActivityThread的binder的引用。对应的实现类是ActivityThread.ApplicationThread。
而ActivityManager.getService()获得的是ActivityManagerService的binder引用对象,ActivityManagerService是实现类。
则最终会通过跨进程binder调用,调用到ActivityManagerService中的startActivity的方法。

三ActivityManagerService部分
这里面会有层层调用,由于不是核心,所以略过,值列出来调用顺序
ActivityManagerService.startActivity
ActivityManagerService.startActivityAsUser四ActivityStarter和ActivityStack部分
非核心逻辑的部分,略过只保留方法调用堆栈
ActivityStarter.startActivityMayWait
ActivityStarter.startActivityLocked
ActivityStarter.startActivity
ActivityStarter.startActivity
ActivityStarter.startActivityUnchecked(控制完整的启动流程的核心逻辑,主要包含下面几个流程)
ActivityStarter.getReusableIntentActivity(); 获取栈中是否存在对应的activity,如果存在,一个逻辑,我们这里先按照主流程走下去,假设stack中不存在对应的activity,后续回过头来在看。
ActivityStackSupervisor.resumeFocusedStackTopActivityLocked
ActivityStack.resumeTopActivityUncheckedLocked
ActivityStack.resumeTopActivityInnerLocked
ActivityStackSupervisor.pauseBackStacks//首先会暂停上一个activity。这里判断上一个的条件就是当前前台运行的PS:这里插一句,如果手机不是很好的,桌面快速连续点开两个APP,你会发现第一个APP先被启动,然后第二个APP也会启动,并盖住第一个APP。那么被暂停的就是第一个APP的activity,而不是启动的桌面activity。
ActivityStackSupervisor.startSpecificActivityLocked//在ActivityStack.resumeTopActivityInnerLocked中被调用,启动activity的主流程
ActivityStackSupervisor.realStartActivityLocked

realStartActivityLocked这个方法中:

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {

        //app对应的是一个用户进程,thead指的就是上面的ApplicationThread的binder引用,所以通过这个binder通知到ApplicationThread调用scheduleLaunchActivity方法,正式回归用户进程。

            app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                    System.identityHashCode(r), r.info,
              ...
        return true;
    }

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);
             //包装activity对象,post到主线程,准备启动
            sendMessage(H.LAUNCH_ACTIVITY, r);
        }

最终会调用到ActivityThread的handleLaunchActivity方法

 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
        //这里包含activity的初始化以及onCreate,onStart方法
        Activity a = performLaunchActivity(r, customIntent);

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            reportSizeConfigurations(r);
            Bundle oldState = r.state;
            //这里会调用resume方法
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
                ...
            
        if (!r.activity.mFinished && r.startsNotResumed) {
                //这里没看懂,后续补充
                performPauseActivityIfNeeded(r, reason);
        }
            ...
        } else {
            //异常情况则结束
            try {
                ActivityManager.getService()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                            Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        }
    }

接下来就是启动方法performLaunchActivity

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        //通过classloader加载对应的activity,反射实例化activity
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            ...
        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            ...
            //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 (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()) {
                    //2调用的是onCreate方法
                    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;
                //3.调用onStart方法,注意,在这之前调用finish方法的话,就不会调用onStart了。
                if (!r.activity.mFinished) {
                    activity.performStart();
                    r.stopped = false;
                }
               ...
            //记录activity对象
            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;
    }

handlerLaunchActivity之后接下来则会调用到handleResumeActivity方法。

final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
        ActivityClientRecord r = mActivities.get(token);
       //会调用到activity的onRsume方法
        r = performResumeActivity(token, clearHide, reason);

           ...
            if (!willBeVisible) {
                try {
                    willBeVisible = ActivityManager.getService().willActivityBeVisible(
                            a.getActivityToken());
                } catch (RemoteException e) {
                    throw e.rethrowFromSystemServer();
                }
            }
            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 (r.mPreserveWindow) {
                    a.mWindowAdded = true;
                    r.mPreserveWindow = false;
                    // Normally the ViewRoot sets up callbacks with the Activity
                    // in addView->ViewRootImpl#setView. If we are instead reusing
                    // the decor view we have to notify the view root that the
                    // callbacks may have changed.
                    ViewRootImpl impl = decor.getViewRootImpl();
                    if (impl != null) {
                        impl.notifyChildRebuilt();
                    }
                }
                if (a.mVisibleFromClient) {
                    if (!a.mWindowAdded) {
                        a.mWindowAdded = true;
//这里会把activity的decor注册到WindowManger上,在这之前哪怕子线程操作UI,也不会触发界面绘制,也就不会出现子线程不能更新UI的异常。
                        wm.addView(decor, l);
                    } else {
                     ...
 if (!r.onlyLocalRequest) {
                r.nextIdle = mNewActivities;
                mNewActivities = r;
                if (localLOGV) Slog.v(
                    TAG, "Scheduling idle handler for " + r);
//这里会触发一个IdleHandler,该IdleHandler的特点就是会在CPU空闲时执行
                Looper.myQueue().addIdleHandler(new Idler());
            }
            ...
    }

第六部分暂停栈顶ac

 private class Idler implements MessageQueue.IdleHandler {
        @Override
        public final boolean queueIdle() {
            ActivityClientRecord a = mNewActivities;//对应的时栈顶的activity的记录
            ...
            if (a != null) {
                mNewActivities = null;
                IActivityManager am = ActivityManager.getService();
                ActivityClientRecord prev;
                ...
                    if (a.activity != null && !a.activity.mFinished) {
                        try {
                            //如果未结束,则通过binder机制跨进程调用activityManager的activityIdle方法
                            am.activityIdle(a.token, a.createdConfig, stopProfiling);
                ...
        }
    }

下面是ActivityManagerService的activityIdle方法

@Override
    public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
        final long origId = Binder.clearCallingIdentity();
        synchronized (this) {
            //根据token获取到对应的ActivityStack
            ActivityStack stack = ActivityRecord.getStackLocked(token);
            if (stack != null) {
                //这里调用activityIdleInternalLocked方法
                ActivityRecord r =
                        mStackSupervisor.activityIdleInternalLocked(token, false /* fromTimeout */,
                                false /* processPausingActivities */, config);
                if (stopProfiling) {
                    if ((mProfileProc == r.app) && (mProfileFd != null)) {
                        try {
                            mProfileFd.close();
                        } catch (IOException e) {
                        }
                        clearProfilerLocked();
                    }
                }
            }
        }
        Binder.restoreCallingIdentity(origId);
    }
ActivityStackSupervisor的activityIdleInternalLocked方法如下:
 final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
            boolean processPausingActivities, Configuration config) {
        ...
        //获取应该暂停的ActivityRecord的结合
        final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
                true /* remove */, processPausingActivities);
        NS = stops != null ? stops.size() : 0;
        if ((NF = mFinishingActivities.size()) > 0) {
            finishes = new ArrayList<>(mFinishingActivities);
            mFinishingActivities.clear();
        }

        if (mStartingUsers.size() > 0) {
            startingUsers = new ArrayList<>(mStartingUsers);
            mStartingUsers.clear();
        }

        //根据ActivityStack中标记的状态,对应的取暂停或者结束对应的Activity
        for (int i = 0; i < NS; i++) {
            r = stops.get(i);
            final ActivityStack stack = r.getStack();
            if (stack != null) {
                if (r.finishing) {
                    stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
                } else {
                    stack.stopActivityLocked(r);//这里会调用触发上一个activity的onStop操作
                }
            }
        }

        //如果有未结束的activity,也会去执行一边触发destroy操作
        // Finish any activities that are scheduled to do so but have been
        // waiting for the next one to start.
        for (int i = 0; i < NF; i++) {
            r = finishes.get(i);
            final ActivityStack stack = r.getStack();
            if (stack != null) {
                activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
            }
        }

        if (!booting) {
            // Complete user switch
            if (startingUsers != null) {
                for (int i = 0; i < startingUsers.size(); i++) {
                    mService.mUserController.finishUserSwitch(startingUsers.get(i));
                }
            }
        }

        mService.trimApplications();
        //dump();
        //mWindowManager.dump();

        if (activityRemoved) {
            resumeFocusedStackTopActivityLocked();
        }

        return r;
    }

启动流程结束------

OK,在看下resume的流程。

 private ActivityRecord getReusableIntentActivity() {
        //FLAG_ACTIVITY_MULTIPLE_TASK对应standard的启动方式,standard/singleTask/singleInstance返回的是true。
        boolean putIntoExistingTask = ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0 &&
                (mLaunchFlags & FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
                || mLaunchSingleInstance || mLaunchSingleTask;
        
        putIntoExistingTask &= mInTask == null && mStartActivity.resultTo == null;
        ActivityRecord intentActivity = null;
        if (mOptions != null && mOptions.getLaunchTaskId() != -1) {
            final TaskRecord task = mSupervisor.anyTaskForIdLocked(mOptions.getLaunchTaskId());
            intentActivity = task != null ? task.getTopActivity() : null;
        } else if (putIntoExistingTask) {
            if (mLaunchSingleInstance) {
                //对应的是singleInstance启动方法,独占一个stack
               intentActivity = mSupervisor.findActivityLocked(mIntent, mStartActivity.info, false);
            } else if ((mLaunchFlags & FLAG_ACTIVITY_LAUNCH_ADJACENT) != 0) {
                
                intentActivity = mSupervisor.findActivityLocked(mIntent, mStartActivity.info,
                        !mLaunchSingleTask);
            } else {
                
                intentActivity = mSupervisor.findTaskLocked(mStartActivity, mSourceDisplayId);
            }
        }
        return intentActivity;
    }
如果走到一个if else分支,则标号就为13、14和13、14、15这样。

1、Activity.startActivityForResult()
2、Instrumentation.execStartActivity(
    this, mMainThread.getApplicationThread(), mToken, this,
    intent, requestCode, options);
3、ActivityManagerService.startActivity(IApplicationThread caller, String callingPackage,Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,int startFlags, ProfilerInfo profilerInfo, Bundle bOptions);
PS:ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
4、ActivityManagerService.startActivityAsUser
5、ActivityStarter.startActivityMayWait
6、ActivityStarter.startActivityLocked
7、ActivityStarter.startActivity
8、ActivityStarter.startActivity
9、ActivityStarter.startActivityUnchecked(控制完整的启动流程的核心逻辑,主要包含下面几个流程)
10、ActivityStarter.getReusableIntentActivity(); 获取栈中是否存在对应的activity,如果存在,一个逻辑,
11、ActivityStarter.setTargetStackAndMoveToFrontIfNeeded(reusedActivity);把已存在的挪到头部
12、

10、ActivityStackSupervisor.resumeFocusedStackTopActivityLocked
11、ActivityStack.resumeTopActivityUncheckedLocked
12、ActivityStack.resumeTopActivityInnerLocked
13、ActivityStackSupervisor.pauseBackStacks(暂停上一个activity,调用处2369行)
14、ActivityStack.startPausingLocked
15、ActivityRecord.ProcessRecord.IApplicationThread.schedulePauseActivity->调用的是ActivityThread.ApplicationThread中的方法
16、ActivityThread.sendMessage发消息通知
17、ActivityThread.handlePauseActivity(H.PAUSE_ACTIVITY)
18、ActivityThread.performPauseActivity
19、ActivityThread.callCallActivityOnSaveInstanceState->Instrumentation.callActivityOnSaveInstanceState->Activity.performSaveInstanceState
20、ActivityThread.performPauseActivityIfNeeded
21、Instrumentation.callActivityOnPause
22、Activity.performPause



13、ActivityStack类2508行,这里的next.app是空的,所以需要走下面的方法创建一个
13、ActivityStackSupervisor.startSpecificActivityLocked
14、ActivityStackSupervisor.realStartActivityLocked
15、ActivityThread.ApplicationThread.scheduleLaunchActivity(app.thread.scheduleLaunchActivity)
16、ActivityThread.sendMessage(H.LAUNCH_ACTIVITY)
17、ActivityThread.handleLaunchActivity
18、ActivityThread.performLaunchActivity
19、Instrumentation.newActivity(反射new一个Activity)
20、Activity.attach
21、Instrumentation.callActivityOnCreate()
22、Activity.performCreate
23、Instrumentation.callActivityOnRestoreInstanceState
24、Activity.performRestoreInstanceState
25、ActivityThread.handleResumeActivity(接上面第18步)
26、Activity.performResume
27、ActivityThread.performPauseActivityIfNeeded()
28、Activity.performPause
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失落夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值