Android Activity启动源码及其应用
开发中经常遇到使用Activity ,网上关于讲解其原理的也很多,但是都是零零散散,今天想做个总结,并且也提高一下自己对源码的认识
Acitivity 启动过程
先看入口
最常用的Activity 启动过程是
@Override
public void startActivity(Intent intent) {
startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
其实我们也可以通过 context.startActivity(next);
来启动Activity ,由于Context是抽象类,Activity是Context子类,所以最后都会走到上一个方法。
显然,从上往下,最终都是由startActivityForResult来实现的
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
if (mParent == null) {
//这里会启动新的Activity,核心功能都在mMainThread.getApplicationThread()中完成
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
//发送结果,即onActivityResult会被调用
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
// If this start is requesting a result, we can avoid making
// the activity visible until the result is received. Setting
// this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
// activity hidden during this time, to avoid flickering.
// This can only be done when a result is requested because
// that guarantees we will get information back when the
// activity is finished, no matter what happens to it.
mStartedActivity = true;
}
final View decor = mWindow != null ? mWindow.peekDecorView() : null;
if (decor != null) {
decor.cancelPendingInputEvents();
}
// TODO Consider clearing/flushing other event sources and events for child windows.
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
我们一行一行看,该方法三个参数都是正常使用时用到的,我们直接看内部,先去判断 mParent 是否为空,这个mParent是什么呢,它其实是一个Activity
在Android 4.1以上,可以指定
android:parentActivityName="MainActivity"
点击打开其他Activity后,可以看到标题栏多了一个返回导航,再点击标题栏的返回时,回到MainActivity,而不是回到之前的Task。只在4.1的机器上有效,在2.x的机器上和以前没有任何区别。
<application ... >
...
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:label="@string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
</application>
一般的Activity其mParent为null,mParent常用在ActivityGroup中,ActivityGroup已废弃,而在ActivityGroup内部的Activity调用startActivity的时候也会走到上面,内部处理逻辑和上面是类似的
也就是说 启动新的Activity是在
mInstrumentation.execStartActivity(this,mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options);
这个方法中,先不考虑mInstrumentation是做什么的,我们看内部实现
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
//核心功能在这个whoThread中完成,其内部scheduleLaunchActivity方法用于完成activity的打开
IApplicationThread whoThread = (IApplicationThread) contextThread;
if (mActivityMonitors != null) {
synchronized (mSync) {
final int N = mActivityMonitors.size();
for (int i=0; i<N; i++) {
final ActivityMonitor am = mActivityMonitors.get(i);
if (am.match(who, null, intent)) {
am.mHits++;
if (am.isBlocking()) {
return requestCode >= 0 ? am.getResult() : null;
}
break;
}
}
}
}
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess();
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, null, options);
//
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
}
return null;
}
往里面看 contextThread 就是之前传入的mMainThread.getApplicationThread()
这个mMainThread 其实是一个Binder对象
对于Binder的原理请看 Android进程间通信(IPC)机制Binder简要介绍
再回到刚才的源码,往下看,先在mActivityMonitors中查找一遍看是否存在这个activity,如果找到了就跳出循环,并且如果可以运行就返回监控器的结果。
对于ActivityMonitor,其实是是google为了自动测试所添加的一个类,可以说是一个工具类,此处我们不深研究,若想了解请看ActivityMonitor 类的功能 ActivityMonitor
接下来在try...catch 里就是真正打开activity的地方,核心功能在whoThread中完成
另外提一下
checkStartActivityResult(result, intent);
这个方法就是专门抛异常的,它会对结果进行检查,如果无法打开activity,则抛出诸如ActivityNotFoundException类似的各种异常
如在xml中没有注册目标activity,Unable to find explicit activity class等
public static void checkStartActivityResult(int res, Object intent) {
if (res >= ActivityManager.START_SUCCESS) {
return;
}
switch (res) {
case ActivityManager.START_INTENT_NOT_RESOLVED:
case ActivityManager.START_CLASS_NOT_FOUND:
if (intent instanceof Intent && ((Intent)intent).getComponent() != null)
throw new ActivityNotFoundException(
"Unable to find explicit activity class "
+ ((Intent)intent).getComponent().toShortString()
+ "; have you declared this activity in your AndroidManifest.xml?");
throw new ActivityNotFoundException(
"No Activity found to handle " + intent);
case ActivityManager.START_PERMISSION_DENIED:
throw new SecurityException("Not allowed to start activity "
+ intent);
case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
throw new AndroidRuntimeException(
"FORWARD_RESULT_FLAG used while also requesting a result");
case ActivityManager.START_NOT_ACTIVITY:
throw new IllegalArgumentException(
"PendingIntent is not an activity");
default:
throw new AndroidRuntimeException("Unknown error code "
+ res + " when starting " + intent);
}
}
接着上文看,在try...catch 中首先是要对传递的数据做准备
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess();```
第一个是将intent里的bundle数据进行处理以便给底层处理,
第二句准备离开应用程序进程,进入ActivityManagerService进程(意味着bundle的数据要在进程间传递)
*关于Intent 的机制请看 [源码角度轻松学习Intent机制](http://www.jianshu.com/p/40ff93eff1a0)*
再接下来就是我们要关注的重点了,也是真正打开activity的地方,核心功能在whoThread中完成。
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, null, options);
//这个方法是专门抛异常的,它会对结果进行检查,如果无法打开activity,
//则抛出诸如ActivityNotFoundException类似的各种异常
checkStartActivityResult(result, intent);
这里 ActivityManagerNative.getDefault() 返回的是一个IActivityManager接口的代理类,
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
IBinder b = ServiceManager.getService("activity");
if (false) {
Log.v("ActivityManager", "default service binder = " + b);
}
IActivityManager am = asInterface(b);
if (false) {
Log.v("ActivityManager", "default service = " + am);
}
return am;
}
};
/**
* 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;
}
return new ActivityManagerProxy(obj);
}
这里我把方法提取了一下,也就是说返回的是一个ActivityManagerProxy对象的引用,其中```ServiceManager.getService("activity");``` 获取了一个系统级的service,而这个Service 实质上就是ActivityManagerService,这里就完成了一个对ActivityManagerService的代理对象ActivityManagerProxy的实例.
>总的来说这里使用的是设计模式中的[代理模式](https://github.com/simple-android-framework-exchange/android_design_patterns_analysis/tree/master/proxy/singwhatiwanna), ActivityManagerProxy和ActivityManagerNative 都实现了IActivityManager,ActivityManagerProxy 就是代理部分,而ActivityManagerNative 就是真实部分,但ActivityManagerNative 是个抽象类,其并不处理过多的具体逻辑,大部分具体逻辑的实现由子类ActivityManagerService 承担,ActivityManagerService 是系统级的Service 并且运行于独立的进程中,而ActivityManagerProxy 也运行于自己的进程中,因此它们两个之间的通信必定是通过跨进程来进行的,也就是基于Android的Binder机制,Binder机制过于复杂。
若想了解Binder机制请参考[[Binder架构解析](http://wangkuiwu.github.io/2014/09/01/Binder-Introduce/#anchor1)](http://wangkuiwu.github.io/2014/09/01/Binder-Introduce/)
关于ActivityManger 请参考[ActivityManger架构解析](http://blog.csdn.net/caowenbin/article/details/6036726)
![ActivityManger运行机制](https://img.haomeiwen.com/i1212336/9a5c2a630b02f2ca.gif?imageMogr2/auto-orient/strip)
也就是说最终是通过Binder IPC到ActivityManagerService所在进程调用ActivityManagerService的startActivity方法
@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());
}
@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
enforceNotIsolatedCaller("startActivity");
userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
false, ALLOW_FULL_ONLY, "startActivity", null);
// TODO: Switch to user app stacks here.
return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, options, userId, null, null);
}
>这个ActivityStackSupervisor类到底是个啥?如果仔细查阅,低版本的Android源码上是没有这个类的;后来AMS的代码进行了部分重构,关于Activity栈管理的部分单独提取出来成为了ActivityStackSupervisor类
继续往里面看,其内部又调用了[startActivityLocked](http://androidxref.com/5.1.1_r6/xref/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java#startActivityLocked)方法,这个方法的作用是在startActivity 前做一系列的检查,如没有在Manifestfest中注册抛出的异常
if (err == ActivityManager.START_SUCCESS && aInfo == null) {
// We couldn't find the specific class specified in the Intent.
// Also the end of the line.
err = ActivityManager.START_CLASS_NOT_FOUND;
}
if (err != ActivityManager.START_SUCCESS) {
if (resultRecord != null) {
resultStack.sendActivityResultLocked(-1,
resultRecord, resultWho, requestCode,
Activity.RESULT_CANCELED, null);
}
ActivityOptions.abort(options);
return err;
}
如果启动不成功就返回这个err,记得在之前mInstrumentation里有个checkStartActivityResult方法么,由它来处理这个信息,并抛出异常。
>activity 在 AMS 中的形式是 ActivityRecord,task 在 AMS 中的形式为TaskRecord,进程在 AMS 中的管理形式为 ProcessRecord
这里还有会处理Activity 的LaunchMode 启动判断,请查看
[Activity LaunchMode源码分析](http://www.jianshu.com/p/09365022adac)
总结可以看下图
![Activity 的启动过程 在ActivityStackSupervisor和ActivityStack 之间的传递顺序](https://img.haomeiwen.com/i1212336/0093b93722c8af42.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
从上图看出,最后走到了ActivityStackSupervisor中的realStartActivityLocked 方法,这个方法中有如下的代码
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
r.compat, r.task.voiceInteractor, app.repProcState, r.icicle, r.persistentState,
results, newIntents, !andResume, mService.isNextTransitionForward(),
profilerInfo);
其中,app.thread的类型为IApplicationThread,
IApplicationThread 是个接口,这个接口继承了IInterFace接口,所以它是一个Binder类型的接口,看到这个接口里的方法我们可以猜测这个接口的实现类完成了启动activity和service的相关功能,而我们要看其中的实现方法就要看它的实现类,还记得上面我们的ApplicationThreadNative么?它继承了IApplicationThread接口,其实他就是这个接口的实现类,进入这个类中我们看一下
![ApplicationThread](https://img.haomeiwen.com/i1212336/7d22225148fb3891.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
总的来说饶了一圈,Activity的启动最终回到了ApplicationThread中,ApplicationThread是通过scheduleLaunchActivity 方法来启动Activity
@Override
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处理,这个Handler就是H,从sendMessage方法看出,它的作用就是发送一个消息给H处理,看一下H对消息的处理方法
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;
case RELAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
ActivityClientRecord r = (ActivityClientRecord)msg.obj;
handleRelaunchActivity(r);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
case PAUSE_ACTIVITY:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
handlePauseActivity((IBinder)msg.obj, false, (msg.arg1&1) != 0, msg.arg2,
(msg.arg1&2) != 0);
maybeSnapshot(); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
case PAUSE_ACTIVITY_FINISHING:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
handlePauseActivity((IBinder)msg.obj, true, (msg.arg1&1) != 0, msg.arg2,
(msg.arg1&1) != 0);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
Handler H 对“LAUNCH_ACTIVITY” 这个消息处理看出,Activity启动是在handleLaunchActivity(r, null); 方法中实现的
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// If we are getting ready to gc after going to the background, well
// we are back active so skip it.
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();
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
Bundle oldState = r.state;
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed);
if (!r.activity.mFinished && r.startsNotResumed) {
// The activity manager actually wants this one to start out
// paused, because it needs to be visible but isn't in the
// foreground. We accomplish this by going through the
// normal startup (because activities expect to go through
// onResume() the first time they run, before their window
// is displayed), and then pausing it. However, in this case
// we do -not- need to do the full pause cycle (of freezing
// and such) because the activity manager assumes it can just
// retain the current state it has.
try {
r.activity.mCalled = false;
mInstrumentation.callActivityOnPause(r.activity);
// We need to keep around the original state, in case
// we need to be created again. But we only do this
// for pre-Honeycomb apps, which always save their state
// when pausing, so we can not have them save their state
// when restarting from a paused state. For HC and later,
// we want to (and can) let the state be saved as the normal
// part of stopping the activity.
if (r.isPreHoneycomb()) {
r.state = oldState;
}
if (!r.activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onPause()");
}
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException(
"Unable to pause activity "
+ r.intent.getComponent().toShortString()
+ ": " + e.toString(), e);
}
}
r.paused = true;
}
} else {
// If there was an error, for any reason, tell the activity
// manager to stop us.
try {
ActivityManagerNative.getDefault()
.finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
} catch (RemoteException ex) {
// Ignore
}
}
}
里面的performLaunchActivity 是真正实现activity的方法
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);
}
//首先从intent中解析出目标activity的启动参数
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();
//用ClassLoader(类加载器)将目标activity的类通过类名加载进来并调用newInstance来实例化一个对象
//其实就是通过Activity的无参构造方法来new一个对象,对象就是在这里new出来的。
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
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 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);
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config);
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被调用了,到此为止,Activity被启动了,接下来的流程就是Activity的生命周期了,
//本文之前已经提到,其生命周期的各种状态的切换由ApplicationThread内部来完成
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.state != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
}
}
if (!r.activity.mFinished) {
activity.mCalled = false;
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;
}
这里面看到
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);
}
}
这个方法就是通过mInstrumentation.newActivity 方法,用classLoader创建activity的实例,这样就创建了Activity,再往下看就是创建Application,以及activity attach的回调方法。