因為要找一找 ContentResolver 的具體實現(xiàn)是在哪里的唠亚,因此拜讀了下 Android 的源碼盟庞,以下就是拜讀過程和思路
getContentResolver()
是定義在 Context 里的, 以下是 Context 的源碼
/** Return a ContentResolver instance for your application's package. */
public abstract ContentResolver getContentResolver();
從關(guān)鍵字 abstract 可以看出 getContentResolver() 是一個抽象方法, 也就是說在子類當(dāng)中吃媒,必然有具體的代碼實現(xiàn)
于是沿著 Activity 的繼承鏈找

在 Context 子類 ContextWrapper 的源碼找到了下面的實現(xiàn)語句:
@Override
public ContentResolver getContentResolver() {
return mBase.getContentResolver();
}
原來 ContextWrapper 將 getContentResolver 外包出去給 mBase, 這里編程當(dāng)中的設(shè)計模式 委托模式颇蜡,將 getContentResolver 交給 mBase 來實現(xiàn)
這時就需從 ContextWrapper(本類中) 找出 mBase 是什么鬼
于是又找到了下面的賦值方法:
/**
* 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;
}
于是就指道了 attachBaseContext 是設(shè)置 mBase 的,這時還未弄得懂 mBase 是什么鬼,需要找出誰調(diào)用了 attachBaseContext 這個方法哼绑,并且傳遞了什么樣的參數(shù),才能弄懂
然后在 Activity 的源碼 中找到 attachBaseContext 的調(diào)用了碉咆,原來是 attach 語句進行了調(diào)用
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor,
Window window) {
// 就是這句了
attachBaseContext(context);
這時就接觸真相了
每次 App 啟動的時候抖韩,都會調(diào)用 Activity 的 attach 方法,而 attach 方法疫铜,傳入的 context 就是類 ContextImp 了茂浮,它的源碼里有 getContentResolver 的實現(xiàn)方法:
@Override
public ContentResolver getContentResolver() {
return mContentResolver;
}
ContextImp 里面也有下面的這一句代碼,對 mContentResolver 進行賦值壳咕,就是這句創(chuàng)造了 Resolver 的了席揽,到此我們就找出了 Resolver 了
mContentResolver = new ApplicationContentResolver(this, mainThread, user);
在 ContextImp 也有類 ApplicationContentResolver 的實現(xiàn),這里就不提下去了
接著就是 ActivityThread 類里面有如何將 Mainfest 創(chuàng)造 content provider 的映射表的實現(xiàn)代碼