ActivityThread源码分析

  一个app应用的入口是一个main函数,在main函数中创建一个ActivityTHread对象  这个对象不是Thread 线程

这里写图片描述

在整个App的入口的源码中 我们可以看到它其实就是普普通通的Java中的main函数
之所以主线程不需要调用Loop。loop()方法就是因为在程序入口就已经默认调用了

public static  void main(String[] args){
         Process.setArgV0("");
         ActivityThread thred=new ActivityThread();
         //传入false表示当前应用为系统应用
         thread.attach(false);
         if(sMainThreadHandler==null){
         sMainThreadHandler=thread.getHandle();
}
         //启动主线程的消息循环
         Looper.loop;
}


函数入口又调用了ActivityThread.attach();方法

  private void attach(boolean system) {
        sCurrentActivityThread = this;
        mSystemThread = system;
        if (!system) {
            ViewRootImpl.addFirstDrawHandler(new Runnable() {
                @Override
                public void run() {
                    ensureJitEnabled();
                }
            });
            android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                    UserHandle.myUserId());
            RuntimeInit.setApplicationObject(mAppThread.asBinder());
            final IActivityManager mgr = ActivityManagerNative.getDefault();
            try {
                mgr.attachApplication(mAppThread);
            } catch (RemoteException ex) {
                // Ignore
            }
    }

他的调用过程如图显示
这里写图片描述

main函数创建了一个ActivityThread对象之后
通过bindler机制 回调了handleLaunchActivity()方法

点:handleLaunchActivity()是通过binder机制调用的
通过handleLaunchActivity()方法内调用了perfromLuanch() handlerResumeActivity()

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {

        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();
        //此时又调用了 performLaunchActivity方法 生成了一个Acitivty对象
        /**
        传入的第二个参数  是一个Intent
        该Intent是用户在Activity跳转时创建
        调用performLaunchActivity()方法
        */
        Activity a = performLaunchActivity(r, customIntent);

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            Bundle oldState = r.state;
            //调用了Resume()方法
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed);
//判断这个Activity的状态  当这个Activity没有调用Resumed()
//就直接finish掉
            if (!r.activity.mFinished && r.startsNotResumed) {

            try {
                ActivityManagerNative.getDefault()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
            } catch (RemoteException ex) {
                // Ignore
            }
        }
    }

//调用Activity的OnReume方法

  final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();
        mSomeActivitiesChanged = true;

        // TODO Push resumeArgs into the activity for consideration
        ActivityClientRecord r = performResumeActivity(token, clearHide);

        if (r != null) {
            final Activity a = r.activity;

            if (localLOGV) Slog.v(
                TAG, "Resume " + r + " started activity: " +
                a.mStartedActivity + ", hideForNow: " + r.hideForNow
                + ", finished: " + a.mFinished);

            final int forwardBit = isForward ?
      //得到窗体Mannager                WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;

            // If the window hasn't yet been added to the window manager,
            // and this guy didn't finish itself or start another activity,
            // then go ahead and add the window.
            boolean willBeVisible = !a.mStartedActivity;
            if (!willBeVisible) {
                try {
                    willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
                            a.getActivityToken());
                } catch (RemoteException e) {
                }
            }
            //当Window为空时创建窗体
            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) {
                    a.mWindowAdded = true;
                    //将DecorView添加到窗体
                    //它是用的WindowManager来添加的
                    //decor是该Activity布局的父容器
                    wm.addView(decor, l);
                }

            // If the window has already been added, but during resume
            // we started another activity, then don't yet make the
            // window visible.
            } else if (!willBeVisible) {
                if (localLOGV) Slog.v(
                    TAG, "Launch " + r + " mStartedActivity set");
                r.hideForNow = true;
            }

            // Get rid of anything left hanging around.
            cleanUpPendingRemoveWindows(r);


    }

performLaunchActivity ()
调用了performLaunchActivity ()方法 返回Activity对象

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

 try {
 /**
 创建了一个Application对象
 */
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);



            if (activity != null) {
            /**
            创建Context对象
            调用了下面的createBaseContextForActivity()方法
            */
                Context appContext = createBaseContextForActivity(r, activity);
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
              /**
这句代码很关键。它将conext对象注入到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);
                        //调用了Activity的OnCreate方法        
                activity.mCalled = false;
                if (r.isPersistable()) {
  mInstrumentation.callActivityOnCreate(activity,        r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
}

createBaseContextForActivity()在上面方法得到调用

private Context createBaseContextForActivity(ActivityClientRecord r,
            final Activity activity) {
            /**
Context 是抽象类 不能被实例化,而ContextImpl为Context的实现类。
这个类被google隐藏了  在Android   Api文档中只能看到Context有两个子类MockContext  和ContextWrap  其实还有ContextImpl 
*/
        ContextImpl appContext = ContextImpl.createActivityContext(this, r.packageInfo, r.token);
        appContext.setOuterContext(activity);
        Context baseContext = appContext;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值