### 四大组件的工作过程
#### 一、集思广益
首先这里转载一些网友的看过本章后的总结和归纳,便于大家理解。
下面这2位通过UML的格式来直观地展示了组件的工作过程,[看云网友的总结](http://www.kancloud.cn/kancloud/art-of-android-development-reading-notes/90454),[amurocrash同学的总结](http://blog.csdn.net/amurocrash/article/details/48858353),这位同学的总结很透彻,另外,CSDN的网友同样写出了自己的归纳总结[总结一](http://blog.csdn.net/qy274770068/article/details/50931853)、[总结二](http://blog.csdn.net/zizidemenghanxiao/article/details/50639025)。
#### 二、具体阐述
##### 一、Activity的工作过程
现附上网友总结的UML图,作为一个大致的了解
![](https://box.kancloud.cn/2016-06-23_576ab842a7c89.png)
1. startActivity:startActivity方法有好几种重载方式,但是它们最终都会调用startActivityForResult方法。
在Activity.java文件中:
~~~
@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);
}
}
~~~
* * * * *
**只需要关注mParent == null这部分逻辑,ActivityGroup最开始被用来在一个界面中嵌入多个Activity,**
**但是其在API13中已经被废弃了,系统推荐采用Fragment来代替ActivityGroup。**
* * * * *
~~~
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
/*
* mParent代表的是ActivityGroup,
* ActivityGroup最开始被用来在一个界面中嵌入多个Activity,
* 但是其在API13中已经被废弃了,系统推荐采用Fragment来代替ActivityGroup。
* */
if (mParent == null) {
/*
* mMainThread.getApplicationThread()这个参数,它的类型是ApplicationThread,
* ApplicationThread是ActivityThread的一个内部类,
* 在后面的分析中可以发现,ApplicationThread和ActivityThread在Activity的启动过程中发挥着很重要的作用。
* */
Instrumentation.ActivityResult ar =
// 所以说Activity的启动过程转移到了Instrumentation中的execStartActivity方法:
mInstrumentation.execStartActivity (this, mMainThread.getApplicationThread (), mToken, this, intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult (
mToken, mEmbeddedID, requestCode, ar.getResultCode (),
ar.getResultData ());
}
if (requestCode >= 0) {
mStartedActivity = true;
}
final View decor = mWindow != null ? mWindow.peekDecorView () : null;
if (decor != null) {
decor.cancelPendingInputEvents ();
}
} else {
if (options != null) {
mParent.startActivityFromChild (this, intent, requestCode, options);
} else {
mParent.startActivityFromChild (this, intent, requestCode);
}
}
}
~~~
* * * * *
**ApplicationThread是ActivityThread的一个内部类,它继承自ApplicationThreadNative,而ApplicationThreadNative继承自Binder并实现了IApplicationThread接口,ApplicationThreadNative的作用其实就和系统为AIDL文件生成的类是一样的。**
* * * * *
Instrumentation的execStartActivity方法:
~~~
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
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();
/*
* 所以启动Activity的真正实现由ActivityManagerNative.getDefault().startActivity方法来完成。
*
* ActivityManagerService继承自ActivityManagerNative,
* 而ActivityManagerNative继承自Binder并实现了IActivityManager这个Binder接口,
* 因此ActivityManagerService也是一个Binder,它是IActivityManager的具体实现。
*
* 由于ActivityManagerNative.getDefault()其实是一个IActivityManager类型的Binder对象,
* 因此它的具体实现是ActivityManagerService(AMS)。
* 所以说Activity的启动过程又转移到了ActivityManagerService中,
* 然后再去看ActivityManagerService的startActivity方法。
* */
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的结果:
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
}
}
~~~
**checkStartActivityResult(result,intent);我们去看看这个方法的源码:可以看出这个方法的作用就是检查启动Activity的结果,当无法正确地启动一个Activity时,这个方法就会抛出异常信息,**
~~~
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)
/*
* 这个异常错误抛出最常见了。
* 如果没有在AndroidManifest中注册Activity,就会抛出此异常。
* */
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);
}
}
~~~
ActivityManagerNative.getDefault实际上就是ActivityManagerService,因此Activity的启动过程转移到了ActivityManagerService(AMS)中。
~~~
/*
* 在Instrumentation的execStartActivity中用ActivityManagerNative的getDefault来获取一个IActivityManager的对象,
* 而且这个IActivityManager的对象其实是一个Binder对象,它的具体实现是ActivityManagerService。
* */
static public IActivityManager getDefault() {
return gDefault.get();
}
/*
* 在ActivityManagernative中,ActivityManagerService这个Binder对象采用单例模式对外提供,
* Singleton是一个单例的封装类,
* 第一次调用它的get方法时它会通过create方法来初始化ActivityManagerService这个Binder对象,
* 在后续的调用中则直接返回之前创建的对象。
* */
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);
}
/*
* 将Binder对象转换成对应IActivityManager的AIDL接口对象:
* */
IActivityManager am = asInterface(b);
if (false) {
Log.v("ActivityManager", "default service = " + am);
}
return am;
}
};
~~~
ActivityManagerService的startActivity方法:
~~~
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags,
String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
/*
* Activity的启动过程又转移到了startActivityAsUser方法中,再进去看看:
* */
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode,
startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
}
~~~
startActivityAsUser方法,在ActivityManagerService.java文件中。
~~~
@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags,
String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
enforceNotIsolatedCaller("startActivity");
userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
false, true, "startActivity", null);
// TODO: Switch to user app stacks here.
return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
null, null, options, userId);
}
~~~
![](https://box.kancloud.cn/2016-06-23_576ab842e0acb.png)
* * * * *
> 从上图可以看出AMS中转移到ActivityStackSupervisor的startActivityMayWait方法。 然后Activity的启动在ActivityStackSupervisor与ActivityStack之间的传递,最终由ApplicationThread的scheduleLaunchActivity方法来启动Activity。发送一个启动Activity的消息交给Handler处理,Handler的名字叫H。
> 最终Activity的启动过程由ActivityThread的handleLaunchActivity方法实现,最后调用performLaunchActivity方法。
* * * * *
ActivityStackSupervisor的realStartActivityLocked方法中有如下一段代码:
~~~
/*
* 这个app.thread的类型为IApplicationThread,
* IApplicationThread继承了IInterface接口,所以它是一个Binder类型的接口。
* 从IApplicationThread声明的接口方法可以看出,它的内部包含了大量启动、停止Activity的接口,
* 此外还包含了启动和停止服务的接口, 从接口方法的命名可以知道,
*IApplicationThread这个Binder接口的实现者完成了大量和Activity以及Service启动和停止相关的功能。
*而IApplicationThread的实现者就是ActivityThread中的内部类ApplicationThread。
*所以,绕来绕去,是用ApplicationThread中的scheduleLaunchActivity来启动Activity的。
*/
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info, new Configuration(
mService.mConfiguration), r.compat,
app.repProcState, r.icicle, results, newIntents,
!andResume, mService.isNextTransitionForward(),
profileFile, profileFd, profileAutoStop);
~~~
IApplicationThread
* * * * *
ApplicationThread继承了ApplicationThreadNative,而ApplicationThreadNative则继承了Binder并实现了IApplicationThread接口。
所以,这个ApplicationThreadNative就是IApplicationThread的实现者。由于ApplicationThreadNative被系统定义为抽象类,所以ApplicationThread就成了IApplicationThread最终的实现者。绕来绕去,是用ApplicationThread中的scheduleLaunchActivity来启动Activity的。
* * * * *
在ApplicationThread中,scheduleLaunchActivity的实现很简单,就是发送一个启动Activity的消息交由Handler处理。这个Handler的名字很简洁,H。
Handler H对消息的处理:
~~~
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
/*
* 启动Activity:
* */
case LAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
ActivityClientRecord r = (ActivityClientRecord)msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
/*
* 又转到这里了:
* */
handleLaunchActivity(r, null);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
...
}
~~~
从handler对“LAUNCH_ACTIVITY”这个消息的处理可以知道,Activity的启动过程由ActivityThread的 handleLaunchActivity这个方法实现,
handleLaunchActivity方法:
~~~
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();
if (r.profileFd != null) {
mProfiler.setProfiler(r.profileFile, r.profileFd);
mProfiler.startProfiling();
mProfiler.autoStopProfiler = r.autoStopProfiler;
}
// Make sure we are running with the most recent config.
handleConfigurationChanged(null, null);
if (localLOGV) Slog.v(
TAG, "Handling launch of " + r);
/*
* 启动Activity终极大Boss在此!!!!
* */
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
Bundle oldState = r.state;
/*
* 调用Activity的onResume方法:
* */
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);
} catch (RemoteException ex) {
// Ignore
}
}
}
~~~
performLaunchActivity方法最终完成了Activity对象的创建和启动过程,且ActivityThread通过handleResumeActivity方法来调用被启动的activity的onResume()这一生命周期方法。
performLaunchActivity主要完成以下几件事
**1. 从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);
}
~~~
**2. 通过Instrumentation的newActivity方法使用类加载器创建Activity对象。**
~~~
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
/*
* 通过类加载器创建Activity的实例对象:
* */
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);
}
}
~~~
**3. 通过LoadedApk的makeApplication方法来尝试创建Application对象,而且一个应用只能有一个Application对象。**
**4. 创建ContextImpl对象并通过Activity的attach方法来完成一些重要数据的初始化。**
**5. 调用Activity的onCreate方法:**
完整代码如下:
~~~
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
/*
* 第一步:从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);
}
/*
* 第二步:通过Instrumentation的newActivity方法使用类加载器创建Activity对象。
* */
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
/*
* 通过类加载器创建Activity的实例对象:
* */
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);
}
}
/*
* 第三步:通过LoadedApk的makeApplication方法来尝试创建Application对象,
* 而且一个应用只能有一个Application对象。
* Application对象的创建也是通过Instrumentation来完成的,这个过程和Activity对象的创建一样,
* 都是通过类加载器来实现的。
* Application创建完毕后,系统会通过Instrumentation的callApplicationOnCreate来调用Application的onCreate方法。
* */
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) {
/*
* 第四步:创建ContextImpl对象并通过Activity的attach方法来完成一些重要数据的初始化。
* 这里有一堆Activity运行过程中所依赖的上下文环境变量,
* 并通过Activity的attach方法来将这些环境变量与Activity相关联:
* (2)ContextImpl是一个很重要的数据结构,它是Context的具体实现,
* Context中改的大部分逻辑都是由ContextImpl来完成的。
* ContextImpl是通过Activity的attach方法来和Activity建立关联的。
* (3)此外,在attach方法中Activity还会完成Window的创建并建立自己和Window的关联,
* 这样当Window接收到外部输入事件后就可以将事件传递给Activity。
* */
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也就完成了整个启动过程,
* 呵呵哒。
* */
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;
}
~~~
以上归纳几点
1. ActivityManagerService(AMS)是Binder,ApplicationThread是Binder。
2. 一个应用只有一个Application对象,它的创建也是通过Instrumentation来完成的,这个过程和Activity对象的创建过程一样,都是通过类加载器来实现的。
3. ContextImpl是Context的具体实现,ContextImpl是通过Activity的attach方法来和Activity建立关联的,在attach方法中Activity还会完成Window的创建并建立自己和Window的关联,这样当window接收到外部输入事件后就可以将事件传递给Activity。
##### 二、Service的工作过程
1. 启动状态
![](https://box.kancloud.cn/2016-06-23_576ab84306890.png)
2. 绑定状态
![](https://box.kancloud.cn/2016-06-23_576ab8432c444.png)
##### 三、BroadcastReceiver 的工作过程
1. 注册(动态注册)
![](https://box.kancloud.cn/2016-06-23_576ab84356b64.png)
2. 发送和接收
![](https://box.kancloud.cn/2016-06-23_576ab843759c4.png)
##### 四、ContentProvider的工作过程
![](https://box.kancloud.cn/2016-06-23_576ab843b2787.png)
- 前言
- 第一章Activity的生命周期和启动模式
- 1.1 Activity生命周期全面分析
- 1.2 Activity的启动模式
- 1.3 IntentFilter的匹配规则
- 第二章IPC
- 转 chapter IPC
- 转IPC1
- 转IPC2
- Binder讲解
- binder
- Messenger
- 一、Android IPC简介
- 二、Android中的多进程模式
- 三、IPC基础概念介绍
- 四、Android中的IPC方式
- 五、Binder连接池
- 第三章
- 第九章四大组件的工作过程
- 第十章
- 第13章 综合技术
- 使用CrashHandler 来获取应用的crash 信息
- 使用Multidex来解决方法数越界
- Android的动态加载技术