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

黑狗不要再黑了發表於2018-11-18

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的建立過程已經分析完畢了。

相關文章