Android入门 —— activity的启动流程源码阅读

来源:互联网 发布:易建联cba数据 编辑:程序博客网 时间:2024/06/05 02:12

Activity启动流程源码阅读

Android API 25 platform
JDK 1.8

在Android中启动一个Activity最常用的的方式就是使用:

Intent intent = new Intent();intent.setClass(CurActivty.this, TargetActivity.class);startActivity(intent);

所以一般阅读源码的时候我们的入手点也是这个函数。下面我们开始对源码进行阅读。因为所有的自定义或者系统定义的Activity最终都是继承的Activity这个类,我们现在开始从这个类的startActivity函数进行分析;

Activity.java
//第一步public void startActivity(Intent intent) {        //调用自己的startActivity重载函数        this.startActivity(intent, null);}
//第二步public void startActivity(Intent intent, @Nullable Bundle options) {        //对options是否为null进行判断        if (options != null) {            //如果为null就传入options            startActivityForResult(intent, -1, options);        } else {            //这里最终的调用和options != null没有区别,只是options最终传入            //的是null            startActivityForResult(intent, -1);        }}
//第三步public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {        //我们将函数中不太相关的的代码省略,发现这个函数又调用了Instrumentation        //的execStartActivity函数            Instrumentation.ActivityResult ar =                mInstrumentation.execStartActivity(                    this, mMainThread.getApplicationThread(), mToken, this,                    intent, requestCode, options);        //... }

通过源码我们知道startActivityForResult调用了Instrumentation这个类的execStartActivity函数。

public ActivityResult execStartActivity(            Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) {//省略部分代码......        try {//省略部分代码......//我们发现这里是调用了ActivityManagerNative这个类中的函数            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) {            throw new RuntimeException("Failure from system", e);        }        return null;    }

通过源码可知ActivityManagerNative类的getDefault()这个函数返回的是一个ActivityManagerProxy实例,ActivityManagerProxy是ActivityManagerNative的一个内部类。在Instrumentation的execStartActivity中最终就是调用的ActivityManagerProxy实例的startActivity函数。

ActivityManagerNative
/** * Retrieve the system's default/global activity manager. * 获取系统全局的 activty manager */static public IActivityManager getDefault() {    //这个gDefault实例是一个单例,如下所示;    return gDefault.get();}//gDefault单例private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {        protected IActivityManager create() {            //这个函数是根据给定的名称获取一个服务的引用,这里很重要。            //它返回的就是一个ActivityManagerService            IBinder b = ServiceManager.getService("activity");            //asInterface返回的就是一个ActivityManagerProxy实例;            IActivityManager am = asInterface(b);            return am;        }}
ActivityManagerProxy
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 {        //这里开始了一个start Activity的事务        mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);}

通过上面的源码可知,在ActivityManagerProxy类的startActivity函数里面我们调用了一个叫
mRemote 的全局变量。这个变量实际上是一个AMS也就是ActivityManagerService,因为:
1.ActivityManagerService继承自ActivityManagerNative
2.ActivityManagerNative继承自Binder
3.Binder是IBinder的实现
4.ServiceManager.getService(“activity”);//这个函数是根据给定的名称获取一个服务的引用源码如下

/*** Returns a reference to a service with the given name.* @param name the name of the service to get* @return a reference to the service, or <code>null</code> if    * the service doesn't exist*/public static IBinder getService(String name) {        try {            IBinder service = sCache.get(name);            if (service != null) {                return service;            } else {                return getIServiceManager().getService(name);            }        } catch (RemoteException e) {            Log.e(TAG, "error in getService", e);        }        return null;    }

也就是说我们Activity启动下一步是在ActivityManagerService中进行,那么我们继续阅读ActivityManagerService中的源码;

ActivityManagerService

我们发现ActivityManagerService本身并没有transact这个方法,这个方法在他的父类Binder中,并且最后调用了ActivityManagerService的onTransact函数,在这个函数中又调用了其父类ActivityManagerNative的onTransact函数;

 @Override    public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {        try {            return super.onTransact(code, data, reply, flags);        } catch (RuntimeException e) {            // The activity manager only throws security exceptions, so let's            // log all others.            if (!(e instanceof SecurityException)) {                Slog.wtf(TAG, "Activity Manager Crash", e);            }            throw e;        }    }

然后代码又回到了我们的ActivityManagerNative中

@Override    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)            throws RemoteException {        switch (code) {        case START_ACTIVITY_TRANSACTION:       //省略部分代码......       //执行子类ActivityManagerService的startActivity函数            int result = startActivity(app, callingPackage, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, options);            return true;        }

回到我们的ActivityManagerService类的startActivity函数,发现他内部直接是调用了他的startActivityAsUser函数;

//第一步 @Override    public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,                resultWho, requestCode, startFlags, profilerInfo, bOptions,                UserHandle.getCallingUserId());    }
//第二步 @Overridepublic final int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {        enforceNotIsolatedCaller("startActivity");        userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, false, ALLOW_FULL_ONLY, "startActivity", null);// TODO: Switch to user app stacks here.return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, null, null, bOptions, false, userId, null, null);}

根据ActivityManagerService的源码,我们发现Activity启动执行到ActivityStarter的startActivityMayWait函数,并且在startActivityMayWait函数最执行startActivityLocked函数;

ActivityStarter
//第一步final int startActivityMayWait(IApplicationThread caller, int callingUid, String callingPackage, Intent intent, String resolvedType, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, IActivityManager.WaitResult outResult, Configuration config, Bundle bOptions, boolean ignoreTargetSecurity, int userId,  IActivityContainer iContainer, TaskRecord inTask) {//省略部分代码......int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity, componentSpecified, outRecord, container, inTask);//省略部分代码......return res;}
//第二步final int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent, String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage, int realCallingPid, int realCallingUid, int startFlags, ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container, TaskRecord inTask) {        int err = ActivityManager.START_SUCCESS;        //省略部分代码......        try {            mService.mWindowManager.deferSurfaceLayout();            //执行startActivityUnchecked            err = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true, options, inTask);        } finally {            mService.mWindowManager.continueSurfaceLayout();        }        //省略部分代码......        return err;}
//第三部private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask) {   //省略部分代码......   //在startActivityUnchecked函数内部会根据不同的状态执行不同的操作,但是最终都会调用   //ActivityStackSupervisor的resumeFocusedStackTopActivityLocked函数。   mSupervisor.resumeFocusedStackTopActivityLocked();   //省略部分代码......   return START_SUCCESS;}

在startActivityUnchecked函数内部会根据不同的状态执行不同的操作,但是最终都会调用ActivityStackSupervisor的resumeFocusedStackTopActivityLocked函数。

ActivityStackSupervisor
boolean resumeFocusedStackTopActivityLocked( ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {  //省略部分代码......  mFocusedStack.resumeTopActivityUncheckedLocked(null, null);  //省略部分代码......        return false;}

从源码看出在resumeFocusedStackTopActivityLocked函数的内部又调用了ActivityStack的resumeTopActivityUncheckedLocked函数

ActivityStack
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {    boolean result = false;    //省略部分代码......     result = resumeTopActivityInnerLocked(prev, options);    //省略部分代码......            return result;}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {   //省略部分代码......    mStackSupervisor.startSpecificActivityLocked(next, true, true);   //省略部分代码......    return true;}

在resumeTopActivityInnerLocked函数中又调用了ActivityStackSupervisor的startSpecificActivityLocked函数,接下来继续看startSpecificActivityLocked

ActivityStackSupervisor
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {    //省略部分代码......       realStartActivityLocked(r, app, andResume, checkConfig);    //省略部分代码......}
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume, boolean checkConfig) throws RemoteException {    //省略部分代码......       app.forceProcessStateUpTo(mService.mTopProcessState);    app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken, System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration), new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results, newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);    //省略部分代码......       return true;}

在ActivityStackSupervisor的realStartActivityLocked函数中我们看到scheduleLaunchActivity被调用了,它是属于IApplicationThread接口的抽象方法,而实现类IApplicationThread的实现类是ApplicationThread,ApplicationThread是ActivityThread类的一个内部类,ApplicationThread继承了抽象类ApplicationThreadNative,而ApplicationThreadNative实现的接口是IApplicationThread,由于ApplicationThreadNative是个抽象类,所以IApplicationThread的最终实现者是ApplicationThread。

private class ApplicationThread extends ApplicationThreadNative {    ......}public abstract class ApplicationThreadNative extends Binder        implements IApplicationThread {    ......}

在ApplicationThread类的scheduleLaunchActivity函数中可以看到这个函数完成了一些列赋值操作并在最后调用sendmessage函数what 为H.LAUNCH_ACTIVITY;

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);    sendMessage(H.LAUNCH_ACTIVITY, r);}

由此可见Activity最终是由一个Handler来启动的

private class H extends Handler {//省略部分代码......public void handleMessage(Message msg) {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);      //启动Activity      handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");                                                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);    } break;//省略部分代码......}

通过当what为LAUNCH_ACTIVITY的message出队时,handleMessage函数中调用handleLaunchActivity函数,handleLaunchActivity函数又调用performLaunchActivity函数正式开始Activity的创建;

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {        //从ActivityClientRecord中获取要装载的Activity信息        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对象    Activity activity = null;    try {       java.lang.ClassLoader cl = r.packageInfo.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);         }     }   try {       //尝试创建Application,如果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) {       //创建ContextImpl       Context appContext = createBaseContextForActivity(r, activity);       CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());       Configuration config = new Configuration(mCompatConfiguration);       if (r.overrideConfig != null) {           config.updateFrom(r.overrideConfig);       }       if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "          + r.activityInfo.name + " with config " + config);       Window window = null;       if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {               window = r.mPendingRemoveWindow;               r.mPendingRemoveWindow = null;               r.mPendingRemoveWindowManager = null;       }        //调用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);            if (customIntent != null) {                activity.mIntent = customIntent;            }            r.lastNonConfigurationInstances = null;            activity.mStartedActivity = false;            int theme = r.activityInfo.getThemeResource();            if (theme != 0) {                activity.setTheme(theme);            }            activity.mCalled = false;            //调用Activity的onCreate函数            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);                  }                }                if (!r.activity.mFinished) {                  activity.mCalled = false;                  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;}
阅读全文
0 0
原创粉丝点击