Application,Activity,Service的创建流程(2)

Activity创建流程

这次从Activity的handleLaunchActivity(...)方法开始分析,因为前面的流程已经在创建Application过程中讲过了。 从代码中我们可以看出Activity是通过performLauncherActivity(...)方法创建的。我们看下这个方法干了啥

private Activity  performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ...
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
                StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            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);
            }
        }
        ...
                if (r.isPersistable()) {
                    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;
                if (!r.activity.mFinished) {
                    activity.performStart();
                    r.stopped = false;
                }
                if (!r.activity.mFinished) {
                    if (r.isPersistable()) {
                        if (r.state != null || r.persistentState != null) {
                            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                                    r.persistentState);
                        }
                    } else if (r.state != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                    }
                }
        ...
        return activity;
    }
复制代码

从代码中我们可以看出:

  1. 首先创建了ContextImpl,然后通过Intrumentation的newActivity(...)来创建Activity的实例。
  2. 然后通过Intrumentation的callActivityOnCreate(...)来调用Activity的onCreate()方法
  3. 通过activity.performStart(...)来调用Activity的onStart()方法
  4. 如果上次Activity被异常杀死,则通过Intrumentation的callActivityOnRestoreInstanceState(...)来执行Activity的performRestoreInstanceState(...)方法
  5. 执行完成后则返回Activity实例并回到handleLaunchActivity(...)方法中,通过handleResumeActivity(...)方法来调用Activity的onResume方法。 以上就是Activity的创建流程.

Service创建流程

AMS完成AMS进程中的Service创建后,通过ApplitionThread的scheduleCreateService(...)方法来通过ActivityThread来创建Client端的Service。下面我们看下scheduleCreateService(...)的源码

        public final void scheduleCreateService(IBinder token,
                ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
            updateProcessState(processState, false);
            CreateServiceData s = new CreateServiceData();
            s.token = token;
            s.info = info;
            s.compatInfo = compatInfo;
            sendMessage(H.CREATE_SERVICE, s);
        }
复制代码

scheduleCreateService(...)方法会发送CREATE_SERVICE给UI线程,下面看看UI线程的针对这个Message干了什么

     public void handleMessage(Message msg) {
           if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
	...
	   case CREATE_SERVICE:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));
                    handleCreateService((CreateServiceData)msg.obj);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
	...
	}
     }
复制代码

UI线程收到CREATE_SERVICE这个message后调用了handleCreateService(...)方法,接着看下handleCreateService(...)干了什么

private void handleCreateService(CreateServiceData data) {
        ...
        LoadedApk loadedApk = getLoadedApkNoCheck(
                data.info.applicationInfo, data.compatInfo);
        Service service = null;
        try {
            java.lang.ClassLoader cl = loadedApk.getClassLoader();
            service = (Service) cl.loadClass(data.info.name).newInstance();
        } catch (Exception e) {
            if (!mInstrumentation.onException(service, e)) {
                throw new RuntimeException(
                    "Unable to instantiate service " + data.info.name + ": " + e.toString(), e);
            }
        }
        try {
            if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
            ContextImpl context = ContextImpl.createAppContext(this, loadedApk);
            context.setOuterContext(service);
            Application app = loadedApk.makeApplication(false, mInstrumentation);
            service.attach(context, this, data.info.name, data.token, app,
                    ActivityManager.getService());
            service.onCreate();
            mServices.put(data.token, service);
            try {
                ActivityManager.getService().serviceDoneExecuting(
                        data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
            } catch (RemoteException e) {
                throw e.rethrowFromSystemServer();
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(service, e)) {
                throw new RuntimeException(
                    "Unable to create service " + data.info.name + ": " + e.toString(), e);
            }
        }
    }
复制代码

从源码中我们可以看出,首先通过ClassLoader来创建Service的实例。然后创建ContextImpl来让Service attach,由此可以证明,Service对应的mBase也为ContextImpl,然后直接调用Service的onCreate()。

由此,Service的创建过程已经分析完毕了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值