Context 相信几乎所有的 Android 开发人员基本上都非常熟悉,因为它太常见了。有大量的场景都离不开 Context,下面列举部分常见场景:
启动 Activity (startActivity)
启动服务 (startService)
发送广播 (sendBroadcast),注册广播接收者 (registerReceiver)
获取 ContentResolver (getContentResolver)
获取类加载器 (getClassLoader)
打开或创建数据库 (openOrCreateDatabase)
获取资源 (getResources)
…
Context 是 Android 中用的非常多的一种概念,常被翻译成上下文,这种概念在其他的技术中也有所使用。Android 官方对它的解释,可以理解为应用程序环境中全局信息的接口,它整合了许多系统级的服务,可以用来获取应用中的类、资源,以及可以进行应用程序级的调起操作,比如启动 Activity、Service 等等,而且 Context 这个类是 abstract 的,不包含具体的函数实现。
Context 是维持 Android 程序中各组件能够正常工作的一个核心功能类。
Context 本身是一个抽象类,其主要实现类为 ContextImpl,另外有直系子类两个:
这两个子类都是 Context 的代理类,它们继承关系如下:
通过 Context 的继承关系图并结合我们开发中比较熟悉的类:Activity、Service、Application,所以我们可以认为 Context 一共有三种类型,分别是 Application、Activity 和 Service,他们分别承担不同的作用,但是都属于 Context,而他们具有 Context 的功能则是由 ContextImpl 类实现的。
简单流程是:Application,Activity 或 Service 通过 attach() 调用父类 ContextWrapper 的 attachBaseContext(),从而设置父类成员变量 mBase 为 ContextImpl 对象,从而核心的工作都交给 ContextImpl 来处理。
根据上面的 Context 类型我们可以知道。Context 一共有 Application、Activity 和 Service 三种类型,因此在一个应用程序中 Context 数量的计算公式可以这样写:
上面的1代表着 Application 的数量,因为一个应用程序中可以有多个 Activity 和多个 Service,但是只能有一个 Application。
要想深入理解 Context,需要依次来看看四大组件的初始化过程。
frameworks/base/core/java/android/app/ActivityThread.java
private Activity performLaunchActivity(ActivityClientRecord r,
Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
//step 1: 创建LoadedApk对象
r.packageInfo = getPackageInfo(aInfo.applicationInfo,
r.compatInfo, Context.CONTEXT_INCLUDE_CODE);
}
...... //component初始化过程
//step 2:创建ContextImpl对象
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
//step 3: 创建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) {
......
}
try {
//step 4: 创建Application对象
Application app =
r.packageInfo.makeApplication(false, mInstrumentation);
......
if (activity != null) {
......
//step 5:将Application/ContextImpl都attach到Activity对象
activity.attach(appContext, this, getInstrumentation(),
r.token, r.ident, app, ......);
......
activity.mCalled = false;
if (r.isPersistable()) {
//step 6: 执行回调onCreate
mInstrumentation.callActivityOnCreate(activity,
r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
if (!activity.mCalled) {
......
}
r.activity = activity;
}
r.setState(ON_CREATE);
.....
} catch (SuperNotCalledException e) {
......
} catch (Exception e) {
......
}
return activity;
}
startActivity 的过程最终会在目标进程执行 performLaunchActivity() 方法,该方法主要功能:
frameworks/base/core/java/android/app/ActivityThread.java
private void handleCreateService(CreateServiceData data) {
......
//step 1: 创建LoadedApk
LoadedApk packageInfo = getPackageInfoNoCheck(
data.info.applicationInfo, data.compatInfo);
Service service = null;
try {
java.lang.ClassLoader cl = packageInfo.getClassLoader();
//step 2: 创建Service对象
service = packageInfo.getAppFactory()
.instantiateService(cl, data.info.name, data.intent);
} catch (Exception e) {
......
}
try {
//step 3: 创建ContextImpl对象
ContextImpl context = ContextImpl.createAppContext(this,
packageInfo);
context.setOuterContext(service);
//step 4: 创建Application对象
Application app = packageInfo.makeApplication(false,
mInstrumentation);
//step 5: 将Application/ContextImpl都attach到service对象
service.attach(context, this, data.info.name,
data.token, app, ActivityManager.getService());
service.onCreate();//step 6: 执行onCreate回调
mServices.put(data.token, service);
try {
ActivityManager.getService().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
} catch (Exception e) {
......
}
}
private void handleReceiver(ReceiverData data) {
......
//step 1: 创建LoadedApk对象
LoadedApk packageInfo = getPackageInfoNoCheck(
data.info.applicationInfo, data.compatInfo);
IActivityManager mgr = ActivityManager.getService();
Application app;
BroadcastReceiver receiver;
ContextImpl context;
try {
//step 2: 创建Application对象
app = packageInfo.makeApplication(false, mInstrumentation);
//step 3: 创建ContextImpl对象
context = (ContextImpl) app.getBaseContext();
if (data.info.splitName != null) {
context = (ContextImpl)
context.createContextForSplit(data.info.splitName);
}
java.lang.ClassLoader cl = context.getClassLoader();
data.intent.setExtrasClassLoader(cl);
data.intent.prepareToEnterProcess();
data.setExtrasClassLoader(cl);
//step 4: 创建BroadcastReceiver对象
receiver = packageInfo.getAppFactory()
.instantiateReceiver(cl, data.info.name, data.intent);
} catch (Exception e) {
......
}
try {
......
//step 5: 执行onReceive回调
receiver.onReceive(context.getReceiverRestrictedContext(),
data.intent);
} catch (Exception e) {
......
} finally {
sCurrentBroadcastIntent.set(null);
}
if (receiver.getPendingResult() != null) {
data.finish();
}
}
private ContentProviderHolder installProvider(Context context,
ContentProviderHolder holder, ProviderInfo info,
boolean noisy, boolean noReleaseNeeded, boolean stable) {
ContentProvider localProvider = null;
IContentProvider provider;
if (holder == null || holder.provider == null) {
......
Context c = null;
ApplicationInfo ai = info.applicationInfo;
if (context.getPackageName().equals(ai.packageName)) {
c = context;
} else if (mInitialApplication != null &&
mInitialApplication.getPackageName().equals(ai.packageName)) {
c = mInitialApplication;
} else {
try {
//step 1 && 2: 创建LoadedApk和ContextImpl对象
c = context.createPackageContext(ai.packageName,
Context.CONTEXT_INCLUDE_CODE);
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
if (c == null) {
......
return null;
}
......
try {
final java.lang.ClassLoader cl = c.getClassLoader();
LoadedApk packageInfo = peekPackageInfo(ai.packageName, true);
if (packageInfo == null) {
// System startup case.
packageInfo = getSystemContext().mPackageInfo;
}
//step 3: 创建ContentProvider对象
localProvider = packageInfo.getAppFactory()
.instantiateProvider(cl, info.name);
provider = localProvider.getIContentProvider();
......
//step 4: ContextImpl都attach到ContentProvider对象
//step 5: 并执行回调onCreate
localProvider.attachInfo(c, info);
} catch (java.lang.Exception e) {
......
}
} else {
......
}
......
return retHolder;
}
private void handleBindApplication(AppBindData data) {
......
//step 1: 创建LoadedApk对象
data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
......
//step 2: 创建ContextImpl对象
final ContextImpl appContext =
ContextImpl.createAppContext(this, data.info);
......
try {
final ClassLoader cl = instrContext.getClassLoader();
//step 3: 创建Instrumentation
mInstrumentation = (Instrumentation)
cl.loadClass(data.instrumentationName.
getClassName()).newInstance();
} catch (Exception e) {
......
}
final ComponentName component = new ComponentName(ii.packageName, ii.name);
mInstrumentation.init(this, instrContext, appContext, component,
data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
......
}
} else {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
}
......
Application app;
......
try {
//step 4: 创建Application对象
app = data.info.makeApplication(data.restrictedBackupMode, null);
......
if (!data.restrictedBackupMode) {
if (!ArrayUtils.isEmpty(data.providers)) {
//step 5: 安装providers
installContentProviders(app, data.providers);
}
}
try {
mInstrumentation.onCreate(data.instrumentationArgs);
}
catch (Exception e) {
......
}
try {
//step 6: 执行Application.Create回调
mInstrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
......
}
} finally {
......
}
......
}
上面介绍了4大组件以及 Application 的初始化过程,接下来再进一步说明其中 LoadedApk,ContextImpl,Application 的初始化过程。
public final LoadedApk getPackageInfo(ApplicationInfo ai,
CompatibilityInfo compatInfo, int flags) {
boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
boolean securityViolation = includeCode && ai.uid != 0
&& ai.uid != Process.SYSTEM_UID &&
(mBoundApplication != null
? !UserHandle.isSameApp(ai.uid,
mBoundApplication.appInfo.uid) : true);
boolean registerPackage = includeCode &&
(flags&Context.CONTEXT_REGISTER_PACKAGE) != 0;
if ((flags&(Context.CONTEXT_INCLUDE_CODE
|Context.CONTEXT_IGNORE_SECURITY))
== Context.CONTEXT_INCLUDE_CODE) {
if (securityViolation) {
//违反隐私问题, 抛出SecurityException
String msg = "Requesting code from " + ai.packageName
+ " (with uid " + ai.uid + ")";
if (mBoundApplication != null) {
msg = msg + " to be run in process "
+ mBoundApplication.processName + " (with uid "
+ mBoundApplication.appInfo.uid + ")";
}
throw new SecurityException(msg);
}
}
return getPackageInfo(ai, compatInfo, null,
securityViolation, includeCode, registerPackage);
}
final ArrayMap<String, WeakReference<LoadedApk>> mPackages =
new ArrayMap<>();
private LoadedApk getPackageInfo(ApplicationInfo aInfo,
CompatibilityInfo compatInfo, ClassLoader baseLoader, ......) {
final boolean differentUser = (UserHandle.myUserId() !=
UserHandle.getUserId(aInfo.uid));
synchronized (mResourcesManager) {
WeakReference<LoadedApk> ref;
if (differentUser) {
// Caching not supported across users
ref = null;
} else if (includeCode) {
ref = mPackages.get(aInfo.packageName);
} else {
ref = mResourcePackages.get(aInfo.packageName);
}
LoadedApk packageInfo = ref != null ? ref.get() : null;
if (packageInfo != null) {
if (!isLoadedApkResourceDirsUpToDate(packageInfo, aInfo)) {
packageInfo.updateApplicationInfo(aInfo, null);
}
return packageInfo;
}
......
packageInfo =
new LoadedApk(this, aInfo, compatInfo, baseLoader,
securityViolation, includeCode
&& (aInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0,
registerPackage);
if (mSystemThread && "android".equals(aInfo.packageName)) {
packageInfo.installSystemApplicationInfo(aInfo,
getSystemContext().mPackageInfo.getClassLoader());
}
if (differentUser) {
// Caching not supported across users
} else if (includeCode) {
mPackages.put(aInfo.packageName,
new WeakReference<LoadedApk>(packageInfo));
} else {
mResourcePackages.put(aInfo.packageName,
new WeakReference<LoadedApk>(packageInfo));
}
return packageInfo;
}
}
public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
CompatibilityInfo compatInfo) {
return getPackageInfo(ai, compatInfo, null, false, true, false);
}
除了 Activity 的初始化,其他组件的初始化都是采用该方法,有默认参数值,主要功能不变。
有了 LoadedApk 对象,接下来可以创建 Application 对象,该对象一个 Apk 只会创建一次。
frameworks/base/core/java/android/app/LoadedApk.java
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
//保证一个LoadedApk对象只创建一个对应的Application对象
if (mApplication != null) {
return mApplication;
}
......
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";//设置应用类名
}
try {
java.lang.ClassLoader cl = getClassLoader();
if (!mPackageName.equals("android")) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
"initializeJavaContextClassLoader");
initializeJavaContextClassLoader();
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
//创建ContextImpl对象
ContextImpl appContext =
ContextImpl.createAppContext(mActivityThread, this);
//创建Application对象, 并将appContext attach到新创建的Application
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {
......
}
mActivityThread.mAllApplications.add(app);
mApplication = app;//将刚创建的app赋值给mApplication
if (instrumentation != null) {
try {
//调用application的OnCreate方法
instrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
......
}
}
......
return app;
}
关于 initializeJavaContextClassLoader() 的过程,将会在Application创建中介绍。
关于应用类名采用的是 Apk 中声明的应用类名,即 Manifest.xml 中定义的类名。有两种特殊情况会强制设置应用类名为 ”android.app.Application”:
public Application newApplication(ClassLoader cl, String className,
Context context) throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
Application app = getFactory(context.getPackageName())
.instantiateApplication(cl, className);
app.attach(context);
return app;
}
创建 ContextImpl 的方式有多种,不同的组件初始化调用不同的方法,如下:
private ContextImpl createBaseContextForActivity(
ActivityClientRecord r) {
final int displayId;
try {
displayId =
ActivityTaskManager.getService().getActivityDisplayId(r.token);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
//创建ContextImpl对象
ContextImpl appContext = ContextImpl.createActivityContext(
this, r.packageInfo, r.activityInfo,
r.token, displayId, r.overrideConfig);
final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
String pkgName = SystemProperties.get("debug.second-display.pkg");
if (pkgName != null && !pkgName.isEmpty()
&& r.packageInfo.mPackageName.contains(pkgName)) {
for (int id : dm.getDisplayIds()) {
if (id != Display.DEFAULT_DISPLAY) {
Display display =
dm.getCompatibleDisplay(id, appContext.getResources());
appContext = (ContextImpl) appContext.createDisplayContext(display);
break;
}
}
}
return appContext;
}
static ContextImpl createActivityContext(ActivityThread mainThread,
LoadedApk packageInfo, ActivityInfo activityInfo,
IBinder activityToken, int displayId,
Configuration overrideConfiguration) {
String[] splitDirs = packageInfo.getSplitResDirs();
ClassLoader classLoader = packageInfo.getClassLoader();
if (packageInfo.getApplicationInfo().
requestsIsolatedSplitLoading()) {
try {
classLoader =
packageInfo.getSplitClassLoader(activityInfo.splitName);
splitDirs = packageInfo.getSplitPaths(activityInfo.splitName);
} catch (NameNotFoundException e) {
......
} finally {
Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
}
}
ContextImpl context = new ContextImpl(null, mainThread,
packageInfo, activityInfo.splitName,
activityToken, null, 0, classLoader, null);
// Clamp display ID to DEFAULT_DISPLAY if it is INVALID_DISPLAY.
displayId = (displayId != Display.INVALID_DISPLAY) ?
displayId : Display.DEFAULT_DISPLAY;
final CompatibilityInfo compatInfo =
(displayId == Display.DEFAULT_DISPLAY)
? packageInfo.getCompatibilityInfo()
: CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;
final ResourcesManager resourcesManager =
ResourcesManager.getInstance();
context.setResources(resourcesManager.
createBaseActivityResources(activityToken,
packageInfo.getResDir(),
splitDirs,
packageInfo.getOverlayDirs(),
packageInfo.getApplicationInfo().sharedLibraryFiles,
displayId,
overrideConfiguration,
compatInfo,
classLoader));
context.mDisplay = resourcesManager.getAdjustedDisplay(displayId,
context.getResources());
return context;
}
Activity 采用该方法来初始化 ContextImpl 对象
static ContextImpl createAppContext(ActivityThread mainThread,
LoadedApk packageInfo) {
return createAppContext(mainThread, packageInfo, null);
}
static ContextImpl createAppContext(ActivityThread mainThread,
LoadedApk packageInfo, String opPackageName) {
ContextImpl context = new ContextImpl(null, mainThread, packageInfo,
null, null, null, 0, null, opPackageName);
context.setResources(packageInfo.getResources());
return context;
}
Service/Application 采用该方法来初始化 ContextImpl 对象
public Context createPackageContext(String packageName, int flags)
throws NameNotFoundException {
return createPackageContextAsUser(packageName, flags, mUser);
}
@Override
public Context createPackageContextAsUser(String packageName,
int flags, UserHandle user) throws NameNotFoundException {
if (packageName.equals("system") ||
packageName.equals("android")) {
// The system resources are loaded in every application,
// so we can safely copy the context without reloading Resources.
return new ContextImpl(this, mMainThread, mPackageInfo,
null, mActivityToken, user, flags, null, null);
}
//创建LoadedApk
LoadedApk pi = mMainThread.getPackageInfo(packageName,
mResources.getCompatibilityInfo(),
flags | CONTEXT_REGISTER_PACKAGE, user.getIdentifier());
if (pi != null) {
ContextImpl c = new ContextImpl(this, mMainThread, pi,
null, mActivityToken, user, flags, null, null);
final int displayId = getDisplayId();
c.setResources(createResources(mActivityToken, pi, null,
displayId, null,
getDisplayAdjustments(displayId).getCompatibilityInfo()));
if (c.mResources != null) {
return c;
}
}
// Should be a better exception.
throw new PackageManager.NameNotFoundException(
"Application package " + packageName + " not found");
}
provider 采用该方法来初始化 ContextImpl 对象
class ContextImpl extends Context {
final ActivityThread mMainThread;
final LoadedApk mPackageInfo;
private final IBinder mActivityToken;
private final String mBasePackageName;
private Context mOuterContext;
//缓存Binder服务
final Object[] mServiceCache =
SystemServiceRegistry.createServiceCache();
private ContextImpl(@Nullable ContextImpl container,
@NonNull ActivityThread mainThread, @NonNull LoadedApk packageInfo,
@Nullable String splitName, @Nullable IBinder activityToken,
@Nullable UserHandle user, int flags,
@Nullable ClassLoader classLoader,
@Nullable String overrideOpPackageName) {
mOuterContext = this; //ContextImpl对象
mMainThread = mainThread; // ActivityThread赋值
mActivityToken = activityToken;
mPackageInfo = packageInfo; // LoadedApk赋值
String opPackageName;
if (container != null) {
mBasePackageName = container.mBasePackageName;
opPackageName = container.mOpPackageName;
setResources(container.mResources);
mDisplay = container.mDisplay;
} else {
mBasePackageName = packageInfo.mPackageName;
ApplicationInfo ainfo = packageInfo.getApplicationInfo();
if (ainfo.uid == Process.SYSTEM_UID &&
ainfo.uid != Process.myUid()) {
opPackageName = ActivityThread.currentPackageName();
} else {
opPackageName = mBasePackageName;
}
}
mOpPackageName = overrideOpPackageName != null ?
overrideOpPackageName : opPackageName;
mContentResolver =
new ApplicationContentResolver(this, mainThread);
}
}
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, ......) {
attachBaseContext(context);//调用父类方法设置mBase.
......
}
将新创建的 ContextImpl 赋值到父类 ContextWrapper.mBase 变量
public final void attach(
Context context,
ActivityThread thread, String className, IBinder token,
Application application, Object activityManager) {
attachBaseContext(context);//调用父类方法设置mBase
mThread = thread; // NOTE: unused - remove?
mClassName = className;
mToken = token;
mApplication = application;
mActivityManager = (IActivityManager)activityManager;
mStartCompatibility = getApplicationInfo().targetSdkVersion
< Build.VERSION_CODES.ECLAIR;
}
final Context getReceiverRestrictedContext() {
if (mReceiverRestrictedContext != null) {
return mReceiverRestrictedContext;
}
return mReceiverRestrictedContext =
new ReceiverRestrictedContext(getOuterContext());
}
对于广播来说 Context 的传递过程,跟其他组件完全不同。广播是在 onCreate 过程通过参数将 ReceiverRestrictedContext 传递过去的。此处 getOuterContext() 返回的是 ContextImpl 对象
framework/base/core/java/android/content/ContentProvider.java
public void attachInfo(Context context, ProviderInfo info) {
attachInfo(context, info, false);
}
private void attachInfo(Context context, ProviderInfo info,
boolean testing) {
mNoPerms = testing;
mCallingPackage = new ThreadLocal<>();
if (mContext == null) {
//将新创建ContextImpl对象保存到ContentProvider对象的成员变量mContext
mContext = context;
if (context != null && mTransport != null) {
mTransport.mAppOpsManager =
(AppOpsManager) context.getSystemService(
Context.APP_OPS_SERVICE);
}
mMyUid = Process.myUid();
if (info != null) {
setReadPermission(info.readPermission);
setWritePermission(info.writePermission);
setPathPermissions(info.pathPermissions);
mExported = info.exported;
mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
setAuthorities(info.authority);
}
// 执行onCreate回调
ContentProvider.this.onCreate();
}
}
final void attach(Context context) {
attachBaseContext(context);
mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}
对象 | 方法 | 返回值类型 | 含义 |
---|---|---|---|
Activity | getApplication() | Application | 获取Activity所属的mApplication |
Service | getApplication() | Application | 获取Service所属的mApplication |
ContextWrapper | getBaseContext | ContextImpl | 获取mBase,即ContextImpl |
ContextWrapper | getApplicationContext | Application | 见小节4.6.1 |
ContextImpl | getApplicationContext | Application | 见小节4.6.1 |
ContextImpl | getOuterContext | ContextImpl | 获取mOuterContext |
ContextImpl | getApplicationInfo | ApplicationInfo | mPackageInfo.mApplicationInfo |
关于 Application
关于 mOuterContext: ContextImpl 的 mOuterContext,默认值是由 ContextImpl 初始化过程创建。但往往通过调用 setOuterContext() 使其指向外部的 Context
@Override
public Context getApplicationContext() {
return (mPackageInfo != null) ?
mPackageInfo.getApplication() :
mMainThread.getApplication();
}
//上述mPackageInfo的数据类型为LoadedApk
public final class LoadedApk {
Application getApplication() {
return mApplication;
}
}
//上述mMainThread为ActivityThread
public final class ActivityThread {
public Application getApplication() {
return mInitialApplication;
}
}
下面用图表来看看核心组件的初始化过程会创建哪些对象
类型 | LoadedApk | ContextImpl | Application | 创建相应对象 | 回调方法 |
---|---|---|---|---|---|
Activity | 是 | 是 | 是 | Activity | onCreate |
Service | 是 | 是 | 是 | Service | onCreate |
Receiver | 是 | 是 | 是 | BroadcastReceiver | onReceive |
Provider | 是 | 是 | 非 | ContentProvider | onCreate |
Application | 是 | 是 | 是 | Application | onCreate |
每个 Apk 都对应唯一的 application 对象和 LoadedApk 对象,当 Apk 中任意组件的创建过程中,当其所对应的的 LoadedApk 和 Application 没有初始化则会创建,且只会创建一次。
另外大家会注意到唯有 Provider 在初始化过程并不会去创建所相应的 Application 对象。也就意味着当有多个 Apk 运行在同一个进程的情况下,第二个 apk 通过 Provider 初始化过程再调用 getContext().getApplicationContext() 返回的并非 Application 对象,而是 NULL。这里要注意会抛出空指针异常。
类型 | startActivity | startService | bindService | sendBroadcast | registerReceiver |
---|---|---|---|---|---|
Activity | 是 | 是 | 是 | 是 | 是 |
Service | - | 是 | 是 | 是 | 是 |
Receiver | - | 是 | × | 是 | - |
Provider | - | 是 | 非 | 是 | 是 |
Application | - | 是 | 是 | 是 | 是 |
说明: (图中第一列代表不同的 Context,“是” 代表允许在该 Context 执行相应的操作;“×” 代表不允许; “-” 代表分情况讨论)
绝大多数情况下,getApplication() 和 getApplicationContext() 这两个方法完全一致,返回值也相同;那么两者到底有什么区别呢?我们来讨论下这个问题:
getApplicationContext() 存在是 Android 历史原因。我们都知道 getApplication() 只存在于 Activity 和 Service 对象;那么对于 BroadcastReceiver 和 ContentProvider 却无法获取 Application,这时就需要一个能在 Context 上下文直接使用的方法,那便是 getApplicationContext()。
两者对比:
当同一个进程有多个 apk 的情况下, 对于第二个 apk 是由 provider 方式拉起的, 前面介绍过 provider 创建过程并不会初始化所在 application,此时执行 getContext().getApplicationContext() 返回的结果便是 NULL。所以对于这种情况要做好判空。