大多数答案已经涵盖getContext() 和getApplicationContext(),但很少解释getBaseContext()。
方法getBaseContext() 仅在您拥有ContextWrapper 时才相关。
Android 提供了一个 ContextWrapper 类,它是围绕现有的 Context 创建的,使用:
ContextWrapper wrapper = new ContextWrapper(context);
使用ContextWrapper 的好处是它可以让您“在不改变原始上下文的情况下修改行为”。例如,如果您有一个名为myActivity 的活动,则可以创建一个主题与myActivity 不同的View:
ContextWrapper customTheme = new ContextWrapper(myActivity) {
@Override
public Resources.Theme getTheme() {
return someTheme;
}
}
View myView = new MyView(customTheme);
ContextWrapper 非常强大,因为它可以让您覆盖Context 提供的大多数功能,包括访问资源的代码(例如openFileInput()、getString())、与其他组件交互(例如sendBroadcast()、registerReceiver()) )、请求权限(例如checkCallingOrSelfPermission())和解析文件系统位置(例如getFilesDir())。 ContextWrapper 对于解决设备/版本特定问题或将一次性自定义应用到需要上下文的视图等组件非常有用。
getBaseContext() 方法可用于访问ContextWrapper 环绕的“基本”上下文。如果需要,您可能需要访问“基本”上下文,例如,检查它是 Service、Activity 还是 Application:
public class CustomToast {
public void makeText(Context context, int resId, int duration) {
while (context instanceof ContextWrapper) {
context = context.baseContext();
}
if (context instanceof Service)) {
throw new RuntimeException("Cannot call this from a service");
}
...
}
}
或者,如果您需要调用方法的“解包”版本:
class MyCustomWrapper extends ContextWrapper {
@Override
public Drawable getWallpaper() {
if (BuildInfo.DEBUG) {
return mDebugBackground;
} else {
return getBaseContext().getWallpaper();
}
}
}