ActivityManagerService and application traffic analysis

Disclaimer: This article is a blogger original article, reproduced welcome but must indicate the source Thank you! https://blog.csdn.net/dongxianfei/article/details/52058109

In the Android application development time, I believe that the most used components should be Activity and Service, you have probably been well aware of the Activity and Life Cycle Service, of course, this is Android's basic skills, but you know Activity and Service how it is to start the system the life cycle when it is called? Today we have the source code from the perspective Preliminary start the process.

The source code is based on the exploration of Android5.1 system, other versions of the system if there are differences in the source code, please analyzed according to their own way.

Prior to the official source code analysis, a brief description of Java classes about the next encounter.

(1)ActivityManagerService.java

Source path \ frameworks \ base \ services \ java \ com \ android \ server \ am \ ActivityManagerService.java, referred to as AMS, is a system-level service management Activity of all, when a start or stop an Activity Activity by the AMS are deregulated, even when out of memory, can take the initiative to kill Activity background, Binder class is a class that can be cross-process communication, and therefore acceptable from the client, such as information Instrumentation, Context and other calls came.

(2)ActivityThread.java

Source path \ frameworks \ base \ core \ java \ android \ app \ main thread class ActivityThread.java, corresponding to the application of such a process, that is, we usually refer to the UI thread, a ActivityThread corresponds to a process, each other entry is the class of the application the main function.

(3)ApplicationThread.java

Source path \ frameworks \ Base \ Core \ the Java \ Android \ App \ ActivityThread.java, the class is ActivityThread.java class inner class, but also a Binder can realize a cross-process communication, mainly used to receive send up from the AMS information, and then further processing.

(4)Instrumentation.java

Source path \ frameworks \ Base \ Core \ Java \ Android \ App \ Instrumentation.java, Activity class is mainly used to operate specific functions, calling AMS method, a Instrumentation class corresponding to a process, each has an inner Activity Instrumentation object references.


Next will enter today's theme, beginning with the application analysis ActivityManagerService how to communicate, we have to start the process step by step Activity to analyze the source code.

1, first look at the three interfaces:

/**
 * Base class for Binder interfaces.  When defining a new interface,
 * you must derive it from IInterface.
 */
public interface IInterface
{
    /**
     * Retrieve the Binder object associated with this interface.
     * You must use this instead of a plain cast, so that proxy objects
     * can return the correct result.
     */
    public IBinder asBinder();
}
Binder base class for other classes are implemented.
/**
 * System private API for talking with the activity manager service.  This
 * provides calls from the application back to the activity manager.
 *
 * {@hide}
 */
public interface IActivityManager extends IInterface {
    public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
            String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flags,
            ProfilerInfo profilerInfo, Bundle options) throws RemoteException;
    public int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent,
            String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flags,
            ProfilerInfo profilerInfo, Bundle options, int userId) throws RemoteException;
    public int startActivityAsCaller(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int flags, ProfilerInfo profilerInfo, Bundle options, int userId) throws RemoteException;
    public WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho,
            int requestCode, int flags, ProfilerInfo profilerInfo, Bundle options,
            int userId) throws RemoteException;
    public int startActivityWithConfig(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho,
            int requestCode, int startFlags, Configuration newConfig,
            Bundle options, int userId) throws RemoteException;
    public int startActivityIntentSender(IApplicationThread caller,
            IntentSender intent, Intent fillInIntent, String resolvedType,
            IBinder resultTo, String resultWho, int requestCode,
            int flagsMask, int flagsValues, Bundle options) throws RemoteException;
    public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
            Intent intent, String resolvedType, IVoiceInteractionSession session,
            IVoiceInteractor interactor, int flags, ProfilerInfo profilerInfo, Bundle options,
            int userId) throws RemoteException;
    public boolean startNextMatchingActivity(IBinder callingActivity,
            Intent intent, Bundle options) throws RemoteException;
    public int startActivityFromRecents(int taskId, Bundle options) throws RemoteException;
    public boolean finishActivity(IBinder token, int code, Intent data, boolean finishTask)
            throws RemoteException;
    public void finishSubActivity(IBinder token, String resultWho, int requestCode) throws RemoteException;
    public boolean finishActivityAffinity(IBinder token) throws RemoteException
...
}
This class is an interface and inherits IInterface, ActivityManagerService base class is used to define the method of operation of a component, such as startActivity, StartService, finishActivity like.
/**
 * System private API for communicating with the application.  This is given to
 * the activity manager by an application  when it starts up, for the activity
 * manager to tell the application about things it needs to do.
 *
 * {@hide}
 */
public interface IApplicationThread extends IInterface {
    void schedulePauseActivity(IBinder token, boolean finished, boolean userLeaving,
            int configChanges, boolean dontReport) throws RemoteException;
    void scheduleStopActivity(IBinder token, boolean showWindow,
            int configChanges) throws RemoteException;
    void scheduleWindowVisibility(IBinder token, boolean showWindow) throws RemoteException;
    void scheduleSleeping(IBinder token, boolean sleeping) throws RemoteException;
    void scheduleResumeActivity(IBinder token, int procState, boolean isForward, Bundle resumeArgs)
            throws RemoteException;
    void scheduleSendResult(IBinder token, List<ResultInfo> results) throws RemoteException;
    void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
            ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
            String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state,
            PersistableBundle persistentState, List<ResultInfo> pendingResults,
            List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward,
            ProfilerInfo profilerInfo) throws RemoteException;
    void scheduleRelaunchActivity(IBinder token, List<ResultInfo> pendingResults,
            List<ReferrerIntent> pendingNewIntents, int configChanges,
            boolean notResumed, Configuration config) throws RemoteException;
    void scheduleNewIntent(List<ReferrerIntent> intent, IBinder token) throws RemoteException;
    void scheduleDestroyActivity(IBinder token, boolean finished,
            int configChanges) throws RemoteException;
    void scheduleReceiver(Intent intent, ActivityInfo info, CompatibilityInfo compatInfo,
...
}

And an interface class is to be inherited IInterface, ApplicationThread base class is used to define the starting and destruction of components, such as scheduleLaunchActivity, schedulePauseActivity, scheduleCreateService like.

Since this article is to start the process of analyzing the main application components, so the cross-process communication Binder involving in this article do temporarily introduced, there will be a special follow-up blog in detail.


2, we have to start Activity start analyzing

There are two ways to start Activity, but whether it is startActivity () or startActivityForResult (), will eventually call the following method Activity

    public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
        if (mParent == null) {
//会调用Instrumentation类的execStartActivity方法
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            if (ar != null) {
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
...
}

Instrumentation seen execStartActivity method calls the class from the code, we enter into the process.

public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
...
        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess();
//在这里会调用了ActivityManagerNative.getDefault().startActivity()方法
            int result = ActivityManagerNative.getDefault()
                .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) {
        }
        return null;
    }
We enter into ActivityManagerNative class, I found the class is an abstract class and inherits Binder, implement the interface IActivityManager before.
public abstract class ActivityManagerNative extends Binder implements IActivityManager
{
    /**
     * Cast a Binder object into an activity manager interface, generating
     * a proxy if needed.
     */
    static public IActivityManager asInterface(IBinder obj) {
        if (obj == null) {
            return null;
        }
        IActivityManager in =
            (IActivityManager)obj.queryLocalInterface(descriptor);
        if (in != null) {
            return in;
        }
//(4)返回ActivityManagerProxy对象
        return new ActivityManagerProxy(obj);
    }

    /**
     * Retrieve the system's default/global activity manager.
     */
//(1)静态getDefault()方法获得IActivityManager对象
    static public IActivityManager getDefault() {
        return gDefault.get();
    }

private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
        protected IActivityManager create() {
//(2)此处的create方法实际上就是(1)处调用的get()方法</span>
            IBinder b = ServiceManager.getService("activity");
            if (false) {
                Log.v("ActivityManager", "default service binder = " + b);
            }
//(3)此处调用asInterface()方法,其实就是ActivityManagerProxy对象,然后返回</span>
            IActivityManager am = asInterface(b);
            if (false) {
                Log.v("ActivityManager", "default service = " + am);
            }
            return am;
        }
    };
}
 
 

By ActivityManagerNative source noted in (1) (2) (3) (4) Step understood, ActivityManagerNative.getDefault () is actually obtained ActivityManagerProxy object (i.e. ActivityManager agent).

So execStartActivity previous methods in, ActivityManagerNative.getDefault (). StartActivity () startActivity method call that is ActivityManagerProxy object startActivity () method.

接下来我们将进入ActivityManagerProxy类的startActivity()方法。

class ActivityManagerProxy implements IActivityManager
//(1)该类实现IActivityManager接口,并实现其所有的抽象方法
{
//(2)该类构造器的形参是一个IBinder对象,即之前asInterface方法传递过来的ServiceManager.getService("activity")的返回值,后通过asBinder方法返回该IBinder对象。
    public ActivityManagerProxy(IBinder remote)
    {
        mRemote = remote;
    }

    public IBinder asBinder()
    {
        return mRemote;
    }

    public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
            String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IActivityManager.descriptor);
        data.writeStrongBinder(caller != null ? caller.asBinder() : null);
        data.writeString(callingPackage);
        intent.writeToParcel(data, 0);
        data.writeString(resolvedType);
        data.writeStrongBinder(resultTo);
        data.writeString(resultWho);
        data.writeInt(requestCode);
        data.writeInt(startFlags);
        if (profilerInfo != null) {
            data.writeInt(1);
            profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
        } else {
            data.writeInt(0);
        }
        if (options != null) {
            data.writeInt(1);
            options.writeToParcel(data, 0);
        } else {
            data.writeInt(0);
        }
        mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
        reply.readException();
        int result = reply.readInt();
        reply.recycle();
        data.recycle();
        return result;
    }
//该类其他的重写方法
public int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent,
            String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flags,
            ProfilerInfo profilerInfo, Bundle options, int userId) throws RemoteException;
    public int startActivityAsCaller(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int flags, ProfilerInfo profilerInfo, Bundle options, int userId) throws RemoteException;
    public WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho,
            int requestCode, int flags, ProfilerInfo profilerInfo, Bundle options,
            int userId) throws RemoteException;
    public int startActivityWithConfig(IApplicationThread caller, String callingPackage,
...
}

进入该类的源码后有三点我们需要重点关注一下:

(1)ActivityManagerProxy类实现IActivityManager接口,并实现其所有的抽象方法。

 
 

(2)该类构造器的参数是IBinder对象,其值即之前asInterface传递过来的参数,最终的值是ServiceManager.getService("activity")的返回值。

(3)该类是一个内部类,是ActivityManagerNative的内部类。

我们继续往下分析,进入StartActivity方法,通过设置一堆参数后最终会调用mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);方法,进而调用ActivityManagerNative类的onTransact方法,其识别码code为START_ACTIVITY_TRANSACTION(对本节调用跳转不是很清楚的可以先了解一下Binder机制)。

接下来我们进入ActivityManagerNative的onTransact方法。

@Override
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
        switch (code) {
        case START_ACTIVITY_TRANSACTION:
        {
            data.enforceInterface(IActivityManager.descriptor);
            IBinder b = data.readStrongBinder();
            IApplicationThread app = ApplicationThreadNative.asInterface(b);
            String callingPackage = data.readString();
            Intent intent = Intent.CREATOR.createFromParcel(data);
            String resolvedType = data.readString();
            IBinder resultTo = data.readStrongBinder();
            String resultWho = data.readString();
            int requestCode = data.readInt();
            int startFlags = data.readInt();
            ProfilerInfo profilerInfo = data.readInt() != 0
                    ? ProfilerInfo.CREATOR.createFromParcel(data) : null;
            Bundle options = data.readInt() != 0
                    ? Bundle.CREATOR.createFromParcel(data) : null;
//(1)调用startActivity方法
            int result = startActivity(app, callingPackage, intent, resolvedType,
                    resultTo, resultWho, requestCode, startFlags, profilerInfo, options);
            reply.writeNoException();
            reply.writeInt(result);
            return true;
        }
...
}

进入到onTransact后发现源码是通过switch条件去进行判断的,找到之前的识别码START_ACTIVITY_TRANSACTION的代码块后,通过设置一堆参数后调用startActivity()方法,这里的startActivity方法的真正实现者其实就是ActivityManagerService类。

这里进入到ActivityManagerService类源码中:

public class ActivityManagerService extends ActivityManagerNative
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
@Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, options,
            UserHandle.getCallingUserId());
    }
...
}

 
 

特别注意该类是继承自ActivityManagerNative类,并重写ActivityManagerNative类的startActivity方法。

好啦,截止到目前为止Activity的启动流程我们已经分析一半了,我们在此画张图来理一下前面几个类的关系。

这张图可以很清晰的表达了几个类之间的关系,根据前面代码的讲解相信大家应该已经了解了。

好啦,接下来我们将进入剩下一半的学习。

之前说进入到ActivityManagerService类的startActivity方法,中间经过一步步调用最终会调用到ApplicationThreadProxy类的scheduleLaunchActivity()方法(这段跳转的中间过程我们以后再分析),ApplicationThreadProxy类和之前ActivityManagerProxy结构基本上是一样的,我们接下来理一下ApplicationThreadProxy类的关系。

ApplicationThreadProxy是ApplicationThreadNative类的内部类,先看一下ApplicationThreadNative的代码

public abstract class ApplicationThreadNative extends Binder
        implements IApplicationThread {
    /**
     * Cast a Binder object into an application thread interface, generating
     * a proxy if needed.
     */
    static public IApplicationThread asInterface(IBinder obj) {
        if (obj == null) {
            return null;
        }
        IApplicationThread in =
            (IApplicationThread)obj.queryLocalInterface(descriptor);
        if (in != null) {
            return in;
        }
        //创建ApplicationThreadProxy对象返回
        return new ApplicationThreadProxy(obj);
    }

public IBinder asBinder()
    {
        return this;
    }

@Override
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
...
return super.onTransact(code, data, reply, flags);
    }
...
}

 
 
 
 
 
 通过这段代码可以发现,ApplicationThreadNative和ActivityManagerNative代码结构都是一样的,我们在来看一下ApplicationThreadProxy的源码。 
 
class ApplicationThreadProxy implements IApplicationThread {
    private final IBinder mRemote;
    
    public ApplicationThreadProxy(IBinder remote) {
        mRemote = remote;
    }
    
    public final IBinder asBinder() {
        return mRemote;
    }

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
            ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
            String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state,
            PersistableBundle persistentState, List<ResultInfo> pendingResults,
            List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward,
            ProfilerInfo profilerInfo) throws RemoteException {
        Parcel data = Parcel.obtain();
        data.writeInterfaceToken(IApplicationThread.descriptor);
        intent.writeToParcel(data, 0);
        data.writeStrongBinder(token);
        data.writeInt(ident);
        info.writeToParcel(data, 0);
        curConfig.writeToParcel(data, 0);
        compatInfo.writeToParcel(data, 0);
        data.writeString(referrer);
        data.writeStrongBinder(voiceInteractor != null ? voiceInteractor.asBinder() : null);
        data.writeInt(procState);
        data.writeBundle(state);
        data.writePersistableBundle(persistentState);
        data.writeTypedList(pendingResults);
        data.writeTypedList(pendingNewIntents);
        data.writeInt(notResumed ? 1 : 0);
        data.writeInt(isForward ? 1 : 0);
        if (profilerInfo != null) {
            data.writeInt(1);
            profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
        } else {
            data.writeInt(0);
        }
//调用onTransact方法中code为SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION的代码
        mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,
                IBinder.FLAG_ONEWAY);
        data.recycle();
    }
...
}

通过以上两段代码可以发现ApplicationThreadNative和ApplicationThreadProxy都实现了IApplicationThread接口,并且和之前的ActivityManager处的代码逻辑是一样的,所以这里就简要概括说明了。

调用ApplicationThreadProxy类的scheduleLaunchActivity()方法后通过识别码SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION会调用到onTransact方法中的SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION条件下,通过设置各种属性后最后调用scheduleLaunchActivity()方法,这个方法的具体实现是在ApplicationThread类中,我们来看一下ApplicationThread类的源码。

private class ApplicationThread extends ApplicationThreadNative {

// we use token to identify this activity without having to send the
        // activity itself back to the activity manager. (matters more with ipc)
        public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Configuration curConfig, 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;

            updatePendingConfiguration(curConfig);
//(1)通过Handler发送code为LAUNCH_ACTIVITY的Message
            sendMessage(H.LAUNCH_ACTIVITY, r);
        }
...
}

ApplicationThread类是ActivityThread类的内部类,并且继承自ApplicationThreadNative类,scheduleLaunchActivity方法通过设置一些参数后最终会通过(1)处的Handler发送Message,然后我们跟踪到handleMessage()方法中

 
 

public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            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);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;
}

可以看出会调用handleLaunchActivity()方法,进入该方法。

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ...

        // Make sure we are running with the most recent config.
        handleConfigurationChanged(null, null);

        // Initialize before creating the activity
        WindowManagerGlobal.initialize();
//(1)此处最终会调用Activity的OnCreate()方法
        Activity a = performLaunchActivity(r, customIntent);

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            Bundle oldState = r.state;
//(2)此处最终会调用Activity的OnResume()方法
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed);
...
}
...
}

(2)处的代码逻辑后面你会发现和(1)处是相同的,所以这里我们就分析一下(1)处的代码,我们进入到performLaunchActivity这个方法中。

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");

        ActivityInfo aInfo = r.activityInfo;
        if (r.packageInfo == null) {
            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                    Context.CONTEXT_INCLUDE_CODE);
        }

        ComponentName component = r.intent.getComponent();
        if (component == null) {
            component = r.intent.resolveActivity(
                mInitialApplication.getPackageManager());
            r.intent.setComponent(component);
        }

        if (r.activityInfo.targetActivity != null) {
            component = new ComponentName(r.activityInfo.packageName,
                    r.activityInfo.targetActivity);
        }

        Activity activity = null;
        try {
            java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
//(1)此处调用Instrumentation对象的newActivity方法,用于创建新的Activity
            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);
            }
        }

        try {
//(2)此处通过makeApplicationf方法创建Application对象
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
            if (localLOGV) Slog.v(
                    TAG, r + ": app=" + app
                    + ", appName=" + app.getPackageName()
                    + ", pkg=" + r.packageInfo.getPackageName()
                    + ", comp=" + r.intent.getComponent().toShortString()
                    + ", dir=" + r.packageInfo.getAppDir());

            if (activity != null) {
                Context appContext = createBaseContextForActivity(r, activity);
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                        + r.activityInfo.name + " with config " + config);
//(3)此处调用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);

                if (customIntent != null) {
                    activity.mIntent = customIntent;
                }
                r.lastNonConfigurationInstances = null;
                activity.mStartedActivity = false;
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    activity.setTheme(theme);
                }

                /* SPRD: add log for activity performance @{ */
                final long onCreateStart = SystemClock.uptimeMillis();
                /* @} */

                activity.mCalled = false;
//(4)此处调用Instrumentation对象的callActivityOnCreate方法
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }

                /* SPRD: add log for activity performance @{ */
                final long onCreateEnd = SystemClock.uptimeMillis();
                String c = component == null ? "null" : component.getClassName();
                String str = c + ", onCreate cost " + (onCreateEnd - onCreateStart) + "ms";
                EventLog.writeEvent(LOG_ON_PERFORMANCE,
                        UserHandle.myUserId(), str);
                /* @} */

                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) {
//(5)此处会调用Instrumentation的callActivityOnRestoreInstanceState方法
                    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);
                    }
                }
                if (!r.activity.mFinished) {
                    activity.mCalled = false;
//(6)此处调用Instrumentation的callActivityOnPostCreate方法
                    if (r.isPersistable()) {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state,
                                r.persistentState);
                    } else {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state);
                    }
                    if (!activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onPostCreate()");
                    }
                }
            }
            r.paused = true;

            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;
    }
由于这个方法的源码较长,所以我们只分析源码中标注序号的部分

(1)处通过ClassLoader加载新的Class类,用于创建Activity,(2)(3)(5)(6)我们目前不做分析,接下来我们重点分析一下(4)处的代码逻辑,此处会调用Instrumentation对象的callActivityOnCreate方法。

/**
     * Perform calling of an activity's {@link Activity#onCreate}
     * method.  The default implementation simply calls through to that method.
     *  @param activity The activity being created.
     * @param icicle The previously frozen state (or null) to pass through to
     * @param persistentState The previously persisted state (or null)
     */
    public void callActivityOnCreate(Activity activity, Bundle icicle,
            PersistableBundle persistentState) {
        prePerformCreate(activity);
        activity.performCreate(icicle, persistentState);
        postPerformCreate(activity);
    }

进入该方法发现其调用了三个方法,其中prePerformCreate和postPerformCreate方法是为调用OnCreate方法做准备和结尾工作,我们重点分析Activity对象的performCreate方法。

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        onCreate(icicle, persistentState);
        mActivityTransitionState.readState(icicle);
        performCreateCommon();
    }
进入该方法终于真相大白了,该方法回调了Activity的OnCreate方法。


Well, that's the bottom half of this article points friends, and as before we use a diagram to show the relationship between various types.


From this figure I believe you already know the inheritance relationship between classes, Well Above is the main content of this blog, then we will be more than content to be a summary.


to sum up

In fact, this blog is mainly explained and other application components such as the Activity Service is or how or from startActivity startService started, until the course of its life cycle method invocation code logic of the whole process is quite complex, class relations Below we will before complete the look of the show.


This figure clearly indicates inheritance relationships between several classes, and the other is between ActivityManagerService and ActivityThread communicate using Binder, so we can also use another figure shows (this figure from the network)


Binder specific communication between the two we will analyze in detail in a future blog, that today, right here, thank you.

Guess you like

Origin blog.csdn.net/dongxianfei/article/details/52058109