你真的弄明白Context了吗?

Context类,应用程序环境的信息(即上下文,环境),是一个抽象类。

public abstract class Context {}

通读该类后发现几乎都是我们平时需要用context调用的抽象方法,比如getResources(),getPackageManager(),getContentResolver(),getApplicationContext(),obtainStyledAttributes(),getSharedPreferences(),startActivity(),checkPermission(),各种服务类型的声明的静态常量等等。还有调用Toast、Dialog需要传入。那么谁来实现这个功能的呢,既然上面Context是一个抽象类,那么肯定有他的实现类。

ContextImpl,Context所有抽象功能的实现类:

class ContextImpl extends Context {
    private Context mOuterContext;
    ......
}

Context的继承类ContextWrapper部分代码,代理Context的实现:

/**
 * 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;
    }
}

ContextThemeWrapper类代码:

/**
 * 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;

ContextThemeWrapper有setTheme()方法:

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

Activity类代码,因为Activity带窗口,需要设置主题,所以需继承于ContextThemeWrapper:

public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback,
        OnCreateContextMenuListener, ComponentCallbacks2,
        Window.OnWindowDismissedCallback, WindowControllerCallback,
        AutofillManager.AutofillClient {
    private static final String TAG = "Activity";
    private static final boolean DEBUG_LIFECYCLE = false;

    /** Standard activity result: operation canceled. */
    public static final int RESULT_CANCELED    = 0;
    /** Standard activity result: operation succeeded. */
    public static final int RESULT_OK           = -1;
    /** Start of user-defined activity results. */
public static final int RESULT_FIRST_USER   = 1;
}

Activity也复写该方法并最终给window设置主题

    @Override
    public void setTheme(int resid) {
        super.setTheme(resid);
        mWindow.setTheme(resid);
    }

Application类代码:

public class Application extends ContextWrapper implements ComponentCallbacks2 {
    private ArrayList<ComponentCallbacks> mComponentCallbacks =
            new ArrayList<ComponentCallbacks>();
    private ArrayList<ActivityLifecycleCallbacks> mActivityLifecycleCallbacks =
            new ArrayList<ActivityLifecycleCallbacks>();
    private ArrayList<OnProvideAssistDataListener> mAssistCallbacks = null;

    /** @hide */
    public LoadedApk mLoadedApk;

    public interface ActivityLifecycleCallbacks {
        void onActivityCreated(Activity activity, Bundle savedInstanceState);
        void onActivityStarted(Activity activity);
        void onActivityResumed(Activity activity);
        void onActivityPaused(Activity activity);
        void onActivityStopped(Activity activity);
        void onActivitySaveInstanceState(Activity activity, Bundle outState);
        void onActivityDestroyed(Activity activity);
  }
}

Service类代码:

public abstract class Service extends ContextWrapper implements ComponentCallbacks2 {
private static final String TAG = "Service";
…
}

继承关系图:


image.png

表述为:
ContextImpl和ContextWrapper继承自Context,ContextThemeWrapper、Application和Service继承自ContextWrapper,Activity继承自ContextThemeWrapper。ContextWrapper和ContextThemeWrapper都是Context的包装类,它们都含有Context类型的mBase对象,mBase具体指向的是ContextImpl,这样通过ContextWrapper和ContextThemeWrapper也可以使用Context的方法。ContextThemeWrapper中包含setTheme()和getTheme()等一些列主题相关的方法,所以需要设置主题的Activity需继承ContextThemeWrapper,让mWindow.setTheme(),而不需要主题的Service则继承ContextWrapper。

那么问题又来了
  • 一个应用有多少个Context?

Application、Activity、Service都间接继承与Context,一个应用有且只有一个Application对象,那么一个应用Context总数为:

Context 数 = Application 数(1) + Activity 数(Activity以及所有子类) + Service 数(Service以及所有子类);

  • 引用是该使用getApplicationcontext还是用Activity才不会引起内存泄漏?

当一个Context销毁的时候,却因为被引用导致销毁失败,导致内存泄露。如一个单例模式的Manager类需要传入一个Context,而这个Manager的对象又需要在Activity中使用,如果我们传递Activity的Context就可能造成内存泄漏,Application的Context对象是随着进程存在的,所以应该传递Application的Context。所以最终注意:尽量不要让生命周期长于Activity的对象引用Activity。

  • getApplication()与getApplicationContext()的爱恨情仇

getApplication()方法属于Activity和Service,获取到的是Activity中的mApplication对象;getApplicationContext()方法属于ContextWrapper,获取到的是ContextWrapper中的Context类对象mBase。
在Activity和Service中可调用getApplication()获取context,而其他以外的组件获取context就只能调用getApplicationContext()。

来自Activity:

    /** Return the application that owns this activity. */
    public final Application getApplication() {
        return mApplication;
    }

来自ContextWrapper:

    @Override
    public Context getApplicationContext() {
        return mBase.getApplicationContext();
    }

打印它们的内存地址发现是相同的,所以getApplication()和getApplicationContext()获取到的是同一对象。

        Application mApplication = getApplication();
        Context mBase = getApplicationContext();

        Log.e("TAG","application " + mApplication);
        Log.e("TAG","context " + mBase);
image.png

关于Context的总结就到这里了,该篇文章会不断更新不断扩充详细,对Context有个更完整认识。

推荐阅读更多精彩内容