Context類,應(yīng)用程序環(huán)境的信息(即上下文诫咱,環(huán)境)笙隙,是一個(gè)抽象類。
public abstract class Context {}
通讀該類后發(fā)現(xiàn)幾乎都是我們平時(shí)需要用context調(diào)用的抽象方法坎缭,比如getResources()竟痰,getPackageManager(),getContentResolver()掏呼,getApplicationContext()坏快,obtainStyledAttributes(),getSharedPreferences(),startActivity(),checkPermission(),各種服務(wù)類型的聲明的靜態(tài)常量等等憎夷。還有調(diào)用Toast莽鸿、Dialog需要傳入。那么誰(shuí)來實(shí)現(xiàn)這個(gè)功能的呢拾给,既然上面Context是一個(gè)抽象類祥得,那么肯定有他的實(shí)現(xiàn)類。
ContextImpl蒋得,Context所有抽象功能的實(shí)現(xiàn)類:
class ContextImpl extends Context {
private Context mOuterContext;
......
}
Context的繼承類ContextWrapper部分代碼级及,代理Context的實(shí)現(xiàn):
/**
* 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類代碼,因?yàn)锳ctivity帶窗口额衙,需要設(shè)置主題饮焦,所以需繼承于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也復(fù)寫該方法并最終給window設(shè)置主題
@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";
…
}
繼承關(guān)系圖:
表述為:
ContextImpl和ContextWrapper繼承自Context怕吴,ContextThemeWrapper、Application和Service繼承自ContextWrapper县踢,Activity繼承自ContextThemeWrapper转绷。ContextWrapper和ContextThemeWrapper都是Context的包裝類,它們都含有Context類型的mBase對(duì)象殿雪,mBase具體指向的是ContextImpl暇咆,這樣通過ContextWrapper和ContextThemeWrapper也可以使用Context的方法。ContextThemeWrapper中包含setTheme()和getTheme()等一些列主題相關(guān)的方法丙曙,所以需要設(shè)置主題的Activity需繼承ContextThemeWrapper爸业,讓mWindow.setTheme(),而不需要主題的Service則繼承ContextWrapper亏镰。
那么問題又來了
-
一個(gè)應(yīng)用有多少個(gè)Context扯旷?
Application、Activity索抓、Service都間接繼承與Context钧忽,一個(gè)應(yīng)用有且只有一個(gè)Application對(duì)象,那么一個(gè)應(yīng)用Context總數(shù)為:
Context 數(shù) = Application 數(shù)(1) + Activity 數(shù)(Activity以及所有子類) + Service 數(shù)(Service以及所有子類);
-
引用是該使用getApplicationcontext還是用Activity才不會(huì)引起內(nèi)存泄漏逼肯?
當(dāng)一個(gè)Context銷毀的時(shí)候耸黑,卻因?yàn)楸灰脤?dǎo)致銷毀失敗,導(dǎo)致內(nèi)存泄露篮幢。如一個(gè)單例模式的Manager類需要傳入一個(gè)Context大刊,而這個(gè)Manager的對(duì)象又需要在Activity中使用,如果我們傳遞Activity的Context就可能造成內(nèi)存泄漏三椿,Application的Context對(duì)象是隨著進(jìn)程存在的缺菌,所以應(yīng)該傳遞Application的Context。所以最終注意:盡量不要讓生命周期長(zhǎng)于Activity的對(duì)象引用Activity搜锰。
-
getApplication()與getApplicationContext()的愛恨情仇
getApplication()方法屬于Activity和Service伴郁,獲取到的是Activity中的mApplication對(duì)象;getApplicationContext()方法屬于ContextWrapper蛋叼,獲取到的是ContextWrapper中的Context類對(duì)象mBase焊傅。
在Activity和Service中可調(diào)用getApplication()獲取context,而其他以外的組件獲取context就只能調(diào)用getApplicationContext()鸦列。
來自Activity:
/** Return the application that owns this activity. */
public final Application getApplication() {
return mApplication;
}
來自ContextWrapper:
@Override
public Context getApplicationContext() {
return mBase.getApplicationContext();
}
打印它們的內(nèi)存地址發(fā)現(xiàn)是相同的租冠,所以getApplication()和getApplicationContext()獲取到的是同一對(duì)象。
Application mApplication = getApplication();
Context mBase = getApplicationContext();
Log.e("TAG","application " + mApplication);
Log.e("TAG","context " + mBase);
關(guān)于Context的總結(jié)就到這里了薯嗤,該篇文章會(huì)不斷更新不斷擴(kuò)充詳細(xì)顽爹,對(duì)Context有個(gè)更完整認(rèn)識(shí)。