大多数答案已经涵盖了getContext()和getApplicationContext()但getBaseContext()很少被解释。
方法getBaseContext()只有当您有ContextWrapper..Android提供了一个ContextWrapper类,该类是围绕现有的Context使用:ContextWrapper wrapper = new ContextWrapper(context);
使用ContextWrapper它允许您“在不更改原始上下文的情况下修改行为”。例如,如果您有一个名为myActivity然后可以创建一个View有着不同的主题myActivity: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();
}
}}