Context

Context

1
public abstract class Context {

之间的继承关系:

image.png

Context 作用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//可以点击studio旁边的 Structure 结构示意图

/**
* 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 的大管家,主要负责:

  • 四大组件,启动 Activity , 广播,服务等
  • 获取系统资源
  • 文件操作相关
  • 数据库操作相关

ContextWrapper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 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;
}

/**
* Set the base context for this ContextWrapper. All calls will then be
* delegated to the base context. Throws
* IllegalStateException if a base context has already been set.
*
* @param base The new base context for this wrapper.
*/
protected void attachBaseContext(Context base) {
if (mBase != null) {
throw new IllegalStateException("Base context already set");
}
mBase = base;
}

/**
* @return the base context as set by the constructor or setBaseContext
*/
public Context getBaseContext() {
return mBase;
}
}

ContextWrapper 实际上就是 Context 的代理类,所有的操作都是 mBase 完成。另外,Activity, Service 的 getBaseContext 返回的就是这个 mBase.

ContextThemeWrapper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/**
* 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;

/**
* Creates a new context wrapper with no theme and no base context.
* <p class="note">
* <strong>Note:</strong> A base context <strong>must</strong> be attached
* using {@link #attachBaseContext(Context)} before calling any other
* method on the newly constructed context wrapper.
*/
public ContextThemeWrapper() {
super(null);
}

/**
* Creates a new context wrapper with the specified theme.
* <p>
* The specified theme will be applied on top of the base context's theme.
* Any attributes not explicitly defined in the theme identified by
* <var>themeResId</var> will retain their original values.
*
* @param base the base context
* @param themeResId the resource ID of the theme to be applied on top of
* the base context's theme
*/
public ContextThemeWrapper(Context base, @StyleRes int themeResId) {
super(base);
mThemeResource = themeResId;
}

/**
* Creates a new context wrapper with the specified theme.
* <p>
* Unlike {@link #ContextThemeWrapper(Context, int)}, the theme passed to
* this constructor will completely replace the base context's theme.
*
* @param base the base context
* @param theme the theme against which resources should be inflated
*/
public ContextThemeWrapper(Context base, Resources.Theme theme) {
super(base);
mTheme = theme;
}

@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
}

/**
* Call to set an "override configuration" on this context -- this is
* a configuration that replies one or more values of the standard
* configuration that is applied to the context. See
* {@link Context#createConfigurationContext(Configuration)} for more
* information.
*
* <p>This method can only be called once, and must be called before any
* calls to {@link #getResources()} or {@link #getAssets()} are made.
*/
public void applyOverrideConfiguration(Configuration overrideConfiguration) {
if (mResources != null) {
throw new IllegalStateException(
"getResources() or getAssets() has already been called");
}
if (mOverrideConfiguration != null) {
throw new IllegalStateException("Override configuration has already been set");
}
mOverrideConfiguration = new Configuration(overrideConfiguration);
}

/**
* Used by ActivityThread to apply the overridden configuration to onConfigurationChange
* callbacks.
* @hide
*/
public Configuration getOverrideConfiguration() {
return mOverrideConfiguration;
}

@Override
public AssetManager getAssets() {
// Ensure we're returning assets with the correct configuration.
return getResourcesInternal().getAssets();
}

@Override
public Resources getResources() {
return getResourcesInternal();
}

private Resources getResourcesInternal() {
if (mResources == null) {
if (mOverrideConfiguration == null) {
mResources = super.getResources();
} else {
final Context resContext = createConfigurationContext(mOverrideConfiguration);
mResources = resContext.getResources();
}
}
return mResources;
}

@Override
public void setTheme(int resid) {
if (mThemeResource != resid) {
mThemeResource = resid;
initializeTheme();
}
}

/** @hide */
@Override
public int getThemeResId() {
return mThemeResource;
}

@Override
public Resources.Theme getTheme() {
if (mTheme != null) {
return mTheme;
}

mThemeResource = Resources.selectDefaultTheme(mThemeResource,
getApplicationInfo().targetSdkVersion);
initializeTheme();

return mTheme;
}

@Override
public Object getSystemService(String name) {
if (LAYOUT_INFLATER_SERVICE.equals(name)) {
if (mInflater == null) {
mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
}
return mInflater;
}
return getBaseContext().getSystemService(name);
}

/**
* Called by {@link #setTheme} and {@link #getTheme} to apply a theme
* resource to the current Theme object. May be overridden to change the
* default (simple) behavior. This method will not be called in multiple
* threads simultaneously.
*
* @param theme the theme being modified
* @param resId the style resource being applied to <var>theme</var>
* @param first {@code true} if this is the first time a style is being
* applied to <var>theme</var>
*/
protected void onApplyThemeResource(Resources.Theme theme, int resId, boolean first) {
theme.applyStyle(resId, true);
}

private void initializeTheme() {
final boolean first = mTheme == null;
if (first) {
mTheme = getResources().newTheme();
final Resources.Theme theme = getBaseContext().getTheme();
if (theme != null) {
mTheme.setTo(theme);
}
}
onApplyThemeResource(mTheme, mThemeResource, first);
}
}

结合注释及源码,可以发现,相比 ContextWrapper, ContextThemeWrapper 有自己的另外的Resource以及 Theme 成员,并且可以传入配置信息以初始化自己的 Resource 及 Theme.

ContextThemeWrapper 和它的mBase 成员在 Resource 以及 Theme 相关的行为上是不同的。

ContextImpl

ContextImplContextThemeWrapper 最大的区别就是没有一个 Configuration. 其它的行为大致一样。 另外 ContextImpl 可以用于创建 Activity ServicemBase 成员,这个 mBase context 除了参数不同,它们的 Resource 也不同, 需要注意的是, createActivityContext等方法中 setResource 是 mBase 自己调用的, Activity, service 以及 Application 本身并没有执行 setResource.

总结

  • ContextWrapper, ContextThemeWrapper 都是 Context 的代理类,二者的区别在于 ContextThemeWrapper 有自己的 Theme 以及 Resource,并且 Resource 可以传入自己配置初始化
  • ContextImpl 是 Context 主要实现类, Activity, Service 和 Application 的 Base contex都是由他创建的,即 ContextWrapper 代理的就是 ContextImpl 对象本身
-------------本文结束感谢您的阅读-------------