The method getBaseContext() is only relevant when you have a ContextWrapper.
Android provides a ContextWrapper class that is created around an existing Context using:
- ContextWrapper wrapper = new ContextWrapper(context);
The benefit of using a ContextWrapper is that it lets you “modify behavior without changing the original Context”. For example, if you have an activity called myActivity then can create a View with a different theme than myActivity:
- ContextWrapper customTheme = new ContextWrapper(myActivity) {
- @Override
- public Resources.Theme getTheme() {
- return someTheme;
- }
- Por favor, no se preocupe.}
- View myView = new MyView(customTheme);
ContextWrapper is really powerful because it lets you override most functions provided by Context including code to access resources (e.g. openFileInput(), getString()), interactuar con otros componentes (ej. sendBroadcast(), registerReceiver()), solicitar permisos (ej. checkCallingOrSelfPermission()) y resolver ubicaciones del sistema de archivos (ej. getFilesDir()). ContextWrapper es realmente útil para trabajar en torno a los problemas específicos del dispositivo/versión o para aplicar personalizaciones puntuales a componentes como Views que requieren un contexto.
El método getBaseContext() se puede utilizar para acceder al Contexto "base" que envuelve el ContextWrapper. You might need to access the “base” context if you need to, for example, check whether it’s a Service, Activity or 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");
- }
- ...
- }
- }
Or if you need to call the “unwrapped” version of a method:
- class MyCustomWrapper extends ContextWrapper {
- @Override
- public Drawable getWallpaper() {
- if (BuildInfo.DEBUG) {
- return debugBackground;
- } else {
- return getBaseContext().getWallpaper();
- }
- }
- }