网上关于 Context 的文章也已经有很多了,好比值得参考的有:android
Android Context彻底解析,你所不知道的Context的各类细节数据库
但看了一下,发现还有值得讨论的地方,好比这个等式:app
Context个数 = Service 个数 + Activity 个数 + 1ide
老实说,我不明白这个等式有什么意义,并且仍是错的。首先多进程状况下,Application 对象就不止一个;其次,Activity、Service、Application 继承自 ContextWrapper,它们本身就是一个 Context,里面又有一个 Base Context;最后,还有各类 outer context、display context 什么的,这部分没深刻研究过,但 Context 的数量绝对大于上述等式的两倍了。oop
上面这部分算一个讨论,下面正式进入正题。ui
Context 自己是一个抽象类,主要实现类为 ContextImpl,另外有子类 ContextWrapper 和 ContextThemeWrapper,这两个子类都是 Context 的代理类,主要区别是 ContextThemeWrapper 有本身的主题资源。它们继承关系以下:this
若是要弄清楚 “某个类有什么用” 这样的问题,其实很简单,看一下它提供了什么接口就知道了,下面列举一些主要的:.net
/** * Interface to global information about an application environment. This is * an abstract class whose implementation is provided by * the Android system. It * allows access to application-specific resources and classes, as well as * up-calls for application-level operations such as launching activities, * broadcasting and receiving intents, etc. */ public abstract class Context { // 四大组件相关 public abstract void startActivity(@RequiresPermission Intent intent); public abstract void sendBroadcast(@RequiresPermission Intent intent); public abstract Intent registerReceiver(@Nullable BroadcastReceiver receiver, IntentFilter filter); public abstract void unregisterReceiver(BroadcastReceiver receiver); public abstract ComponentName startService(Intent service); public abstract boolean stopService(Intent service); public abstract boolean bindService(@RequiresPermission Intent service, @NonNull ServiceConnection conn, @BindServiceFlags int flags); public abstract void unbindService(@NonNull ServiceConnection conn); public abstract ContentResolver getContentResolver(); // 获取系统/应用资源 public abstract AssetManager getAssets(); public abstract Resources getResources(); public abstract PackageManager getPackageManager(); public abstract Context getApplicationContext(); public abstract ClassLoader getClassLoader(); public final @Nullable <T> T getSystemService(@NonNull Class<T> serviceClass) { ... } public final String getString(@StringRes int resId) { ... } public final int getColor(@ColorRes int id) { ... } public final Drawable getDrawable(@DrawableRes int id) { ... } public abstract Resources.Theme getTheme(); public abstract void setTheme(@StyleRes int resid); public final TypedArray obtainStyledAttributes(@StyleableRes int[] attrs) { ... } // 获取应用相关信息 public abstract ApplicationInfo getApplicationInfo(); public abstract String getPackageName(); public abstract Looper getMainLooper(); public abstract int checkPermission(@NonNull String permission, int pid, int uid); // 文件相关 public abstract File getSharedPreferencesPath(String name); public abstract File getDataDir(); public abstract boolean deleteFile(String name); public abstract File getExternalFilesDir(@Nullable String type); public abstract File getCacheDir(); ... public abstract SharedPreferences getSharedPreferences(String name, @PreferencesMode int mode); public abstract boolean deleteSharedPreferences(String name); // 数据库相关 public abstract SQLiteDatabase openOrCreateDatabase(...); public abstract boolean deleteDatabase(String name); public abstract File getDatabasePath(String name); ... // 其它 public void registerComponentCallbacks(ComponentCallbacks callback) { ... } public void unregisterComponentCallbacks(ComponentCallbacks callback) { ... } ... } public interface ComponentCallbacks { void onConfigurationChanged(Configuration newConfig); void onLowMemory(); }
结合注释,能够发现,Context 就至关于 Application 的大管家,主要负责:代理
先看 ContextWrapper:
/** * Proxying implementation of Context that simply delegates all of its calls to * another Context. Can be subclassed to modify behavior without changing * the original Context. */ public class ContextWrapper extends Context { // 注意这个成员 Context mBase; public ContextWrapper(Context base) { mBase = base; } protected void attachBaseContext(Context base) { if (mBase != null) { throw new IllegalStateException("Base context already set"); } mBase = base; } // 这就是常常让人产生疑惑的 Base Context 了 public Context getBaseContext() { return mBase; } // 下面这些方法全都直接经过 mBase 完成 @Override public AssetManager getAssets() { return mBase.getAssets(); } @Override public Resources getResources() { return mBase.getResources(); } @Override public PackageManager getPackageManager() { return mBase.getPackageManager(); } ... }
能够看到,ContextWrapper 实际上就是 Context 的代理类而已,全部的操做都是经过内部成员 mBase 完成的,另外,Activity、Service 的 getBaseContext 返回的就是这个 mBase。
接着看 ContextThemeWrapper,这个类的代码并很少,主要看 Resource 和 Theme 相关的:
/** * A context wrapper that allows you to modify or replace the theme of the * wrapped context. */ public class ContextThemeWrapper extends ContextWrapper { private int mThemeResource; private Resources.Theme mTheme; private LayoutInflater mInflater; private Configuration mOverrideConfiguration; private Resources mResources; public ContextThemeWrapper() { super(null); } public ContextThemeWrapper(Context base, @StyleRes int themeResId) { super(base); mThemeResource = themeResId; } public ContextThemeWrapper(Context base, Resources.Theme theme) { super(base); mTheme = theme; } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(newBase); } // 在 Recource 初始化以前,传入配置信息 public void applyOverrideConfiguration(Configuration overrideConfiguration) { if (mResources != null) { throw new IllegalStateException(...); } if (mOverrideConfiguration != null) { throw new IllegalStateException(...); } mOverrideConfiguration = new Configuration(overrideConfiguration); } public Configuration getOverrideConfiguration() { return mOverrideConfiguration; } // 没有重写 setResource,即 setResource 行为和父类同样 @Override public Resources getResources() { return getResourcesInternal(); } private Resources getResourcesInternal() { if (mResources == null) { if (mOverrideConfiguration == null) { mResources = super.getResources(); } else { // 根据配置信息初始化 Resource // 注意,这里建立了另外一个和 Base Context 不一样的 Resource final Context resContext = createConfigurationContext(mOverrideConfiguration); mResources = resContext.getResources(); } } return mResources; } @Override public void setTheme(int resid) { if (mThemeResource != resid) { mThemeResource = resid; initializeTheme(); } } private void initializeTheme() { final boolean first = mTheme == null; if (first) { // 根据 Resource 获取 Theme mTheme = getResources().newTheme(); // 复制内容 final Resources.Theme theme = getBaseContext().getTheme(); if (theme != null) { mTheme.setTo(theme); } } onApplyThemeResource(mTheme, mThemeResource, first); } protected void onApplyThemeResource(Resources.Theme theme, int resId, boolean first) { theme.applyStyle(resId, true); } @Override public Resources.Theme getTheme() { // 只会初始化一次 if (mTheme != null) { return mTheme; } mThemeResource = Resources.selectDefaultTheme(mThemeResource, getApplicationInfo().targetSdkVersion); initializeTheme(); return mTheme; } ... }
结合注释及源码,能够发现,相比 ContextWrapper,ContextThemeWrapper 有本身的另外 Resource 以及 Theme 成员,而且能够传入配置信息以初始化本身的 Resource 及 Theme。即 Resource 以及 Theme 相关的行为再也不是直接调用 mBase 的方法了,也就说,ContextThemeWrapper 和它的 mBase 成员在 Resource 以及 Theme 相关的行为上是不一样的。
下面看一下 ContextImpl 有关 Theme 以及 Resource 的部分,以分析它和 ContextThemeWrapper 的区别:
/** * Common implementation of Context API, which provides the base * context object for Activity and other application components. */ class ContextImpl extends Context { private int mThemeResource = 0; private Resources.Theme mTheme = null; private @NonNull Resources mResources; // 用于建立 Activity Context static ContextImpl createActivityContext(...) { ContextImpl context = new ContextImpl(...); context.setResources(resourcesManager.createBaseActivityResources(...)); return context; } // 用于建立 Application Context、Service Context static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) { ContextImpl context = new ContextImpl(...); context.setResources(packageInfo.getResources()); return context; } private static Resources createResources(...) { return ResourcesManager.getInstance().getResources(...); } // ContextThemeWrapper 没有重写父类的 setResources // 所以会调用 mBase 的 setResources,即和 ContextImpl 的行为同样 void setResources(Resources r) { if (r instanceof CompatResources) { ((CompatResources) r).setContext(this); } mResources = r; } @Override public Resources getResources() { return mResources; } /* ---------- 主题相关 ------------ */ @Override public void setTheme(int resId) { synchronized (mSync) { if (mThemeResource != resId) { mThemeResource = resId; initializeTheme(); } } } // 直接建立一个 Themem 对象,相比 ContextThemeWrapper,少了一部份内容 private void initializeTheme() { if (mTheme == null) { mTheme = mResources.newTheme(); } mTheme.applyStyle(mThemeResource, true); } @Override public Resources.Theme getTheme() { synchronized (mSync) { // 和 ContextThemeWrapper 基本同样 if (mTheme != null) { return mTheme; } mThemeResource = Resources.selectDefaultTheme(mThemeResource, getOuterContext().getApplicationInfo().targetSdkVersion); initializeTheme(); return mTheme; } } }
从代码中能够看出,ContextImpl 和 ContextThemeWrapper 最大的区别就是没有一个 Configuration 而已,其它的行为大体是同样的。另外,ContextImpl 能够用于建立 Activity、Service 以及 Application 的 mBase 成员,这个 Base Context 时除了参数不一样,它们的 Resource 也不一样。须要注意的是,createActivityContext 等方法中 setResource 是 mBase 本身调用的,Activity、Service 以及 Application 自己并无执行 setResource。
ContextWrapper、ContextThemeWrapper 都是 Context 的代理类,两者的区别在于 ContextThemeWrapper 有本身的 Theme 以及 Resource,而且 Resource 能够传入本身的配置初始化
ContextImpl 是 Context 的主要实现类,Activity、Service 和 Application 的 Base Context 都是由它建立的,即 ContextWrapper 代理的就是 ContextImpl 对象自己
ContextImpl 和 ContextThemeWrapper 的主要区别是, ContextThemeWrapper 有 Configuration 对象,Resource 能够根据这个对象来初始化
Service 和 Application 使用同一个 Recource,和 Activity 使用的 Resource 不一样
先看 Activity,Activity 在启动时,最终会执行 ActivityThread 的 performLaunchActivitiy:
public final class ActivityThread { private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { ... // 这个 Context 将会做为 Activity 的 Base Context ContextImpl appContext = createBaseContextForActivity(r); Activity activity = null; try { ClassLoader cl = appContext.getClassLoader(); // 建立 Activity activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent); StrictMode.incrementExpectedActivityCount(activity.getClass()); } catch (Exception e) { ... } try { // 建立 Application Application app = r.packageInfo.makeApplication(false, mInstrumentation); if (activity != null) { // 初始化 Activity,注意参数 appContext activity.attach(appContext, ...); ... } } catch (...) { ... } return activity; } private ContextImpl createBaseContextForActivity(ActivityClientRecord r) { ContextImpl appContext = ContextImpl.createActivityContext(...); ... } }
能够看到,Activity 的 Base Context 就是上面分析过的 ContextImpl 的 createActivityContext 建立的。
同时,Service 的 Base Context 的建立过程和 Application 同样,调用的都是 ContextImpl 的 createAppContext,即 Service Context 和 Application Context 的 Resource 是相同的。所以这里跳过 Service,下面看一下 Application Context。
在上面 ActivityThread 的 performLaunchActivity 方法中,能够看到一个 makeApplication 的调用,它是 LoaedApk 的方法:
public final class LoadedApk { private Application mApplication; public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) { if (mApplication != null) { return mApplication; } Application app = null; try { // 建立 Base Context ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this); // 建立 Application 并设置 Base Context app = mActivityThread.mInstrumentation.newApplication( cl, appClass, appContext); appContext.setOuterContext(app); } catch (Exception e) { ... } // Application 建立成功,赋值给 mApplication mApplication = app; ... return app; } // 获取 mApplication Application getApplication() { return mApplication; } }
public class Application extends ContextWrapper implements ComponentCallbacks2 { /* package */ final void attach(Context context) { // 调用父类的 attachBaseContext 以设置 mBase attachBaseContext(context); } }
能够看到,Instrumentation 是使用反射的方法建立 Application 对象,建立完毕后,会执行 Application 的 attach 方法设置 mBase 成员。
Application 及其 Base Context 的建立过程咱们了解了,接下来看一下 getApplicationContext 的实现:
class ContextImpl extends Context { ActivityThread mMainThread; LoadedApk mPackageInfo; @Override public Context getApplicationContext() { return (mPackageInfo != null) ? mPackageInfo.getApplication() : mMainThread.getApplication(); } }
从代码中能够看出,getApplicationContext 的返回值可能有两个:第一个是 LoadedApk 的 getApplication 方法,这个方法的返回值就是刚刚建立的 Application 对象;第二个是 ActivityThread 的 getApplication 方法:
public final class ActivityThread { Application mInitialApplication; public Application getApplication() { return mInitialApplication; } public static ActivityThread systemMain() { // 建立 ActivityThread ActivityThread thread = new ActivityThread(); thread.attach(true); return thread; } private void attach(boolean system) { mSystemThread = system; if (!system) { ... } else { try { mInstrumentation = new Instrumentation(); // 注意参数 getSystemContext().mPackageInfo ContextImpl context = ContextImpl.createAppContext( this, getSystemContext().mPackageInfo); // 建立 Application mInitialApplication = context.mPackageInfo.makeApplication(true, null); mInitialApplication.onCreate(); } catch (Exception e) { ... } } ... } }
ActivityThread 中的 mInitialApplication 是在 systemMain 方法执行时建立的,而这个方法又是 SystemServer 启动时调用的,结合参数 getSystemContext().mPackageInfo,所以我的推测 mInitialApplication 对应的是系统的某个 apk,即系统级别的 Application,但具体是否是这样,目前尚未深刻研究过,有兴趣的能够本身研究。
通常状况下,使用代理而不直接使用某个对象,目的可能有两个:
其中 Servcie 和 Application 的父类 ContextWrapper 彻底没有自定义的行为,而 Activity 的父类 ContextThemeWrapper 则自定义了 Resource 以及 Theme 的相关行为,所以,我的理解:
对于 Activity 的 getResource 问题,我写了一份代码来验证:
public class MainActivity extends AppCompatActivity { private Configuration mOverrideConfiguration; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i(TAG, "getResources: " + getResources() + ", getBaseContext().getResources():" + getBaseContext().getResources()); } // 由于 Android 会在 onCreate 以前自动调用 getResource // 所以须要在这里执行 applyOverrideConfiguration @Override public Resources getResources() { if (mOverrideConfiguration == null) { mOverrideConfiguration = new Configuration(); applyOverrideConfiguration(mOverrideConfiguration); } return super.getResources(); } }
输出(我用的是小米手机):
getResources: android.content.res.MiuiResources@3c660a7, getBaseContext().getResources():android.content.res.MiuiResources@5143954
能够看到,就像源码显示的那样,应用了 Configuration 以后,Activity 的 getResource 方法返回的和 getBaseContext().getResources() 方法返回的不是同一个对象
Context 的继承关系以下:
Context 至关于 Application 的大管家,主要负责:
ContextWrapper、ContextThemeWrapper、ContextImpl 的区别:
Activity Context、Service Context、Application Context、Base Context 的区别: