Android10.0 ContentProvider工作過程源碼解析

本文出自門心叼龍的博客疾嗅,屬于原創(chuàng)類容珠十,轉(zhuǎn)載請(qǐng)注明出處。

今天寫的這篇已經(jīng)源碼解析的第六篇了荠诬,雖然這類文章不如實(shí)戰(zhàn)類文章受眾那么廣琅翻,但是作為每個(gè)Android開發(fā)工程師來講,加強(qiáng)內(nèi)功修煉這是作為向高級(jí)工程師邁進(jìn)的必經(jīng)之路柑贞。要知道了解了底層的工作原理對(duì)于以后實(shí)戰(zhàn)開發(fā)中出現(xiàn)的各種各樣的問題都會(huì)輕易解決方椎。這和習(xí)武是一個(gè)道理,如果一個(gè)人它的內(nèi)功很強(qiáng)钧嘶,那它學(xué)什么都很快很容易掌握棠众,否則它永遠(yuǎn)只是個(gè)花架子。
好了有决,言歸正傳闸拿,我們?cè)谌粘i_發(fā)過程中經(jīng)常需要訪問照片應(yīng)用中圖片資源,或者讀取通訊錄應(yīng)用當(dāng)中的聯(lián)系人信息等等的一些應(yīng)用場(chǎng)景书幕,這時(shí)候就需要用到ContentProvider新荤,ConentProvider在Android四大組件中排行老四,它是一個(gè)國家圖書館台汇,為不同的應(yīng)用程序之間的數(shù)據(jù)共享提供了統(tǒng)一的訪問接口苛骨,它需要和ContentResolver配合使用,ContentProvider負(fù)責(zé)提供數(shù)據(jù)苟呐,ContentResolver負(fù)責(zé)獲取數(shù)據(jù)痒芝。在應(yīng)用程序啟動(dòng)的時(shí)候,ContentProvider就會(huì)被初始化注冊(cè)到ActivityManagerServcie牵素,然后其他的應(yīng)用通過uri向服務(wù)端獲取ConentProvider所對(duì)應(yīng)的Transport對(duì)象严衬。Transport本質(zhì)上是一個(gè)binder,有了binder這個(gè)中間人對(duì)象两波,我們就可以調(diào)用遠(yuǎn)程的ConentProvider所提供的方法了瞳步。和之前一樣,我先先來回顧一下ContentProvider的簡(jiǎn)單使用腰奋,然后在對(duì)它的源碼進(jìn)行解析单起。

ContentProvider的基本用法

定義ContentProvider

自定義一個(gè)ContentProvider很簡(jiǎn)單,我只需要繼承ContentProvider劣坊,并復(fù)寫的它的增刪改查方法即可嘀倒,具體代碼實(shí)現(xiàn)如下:

public class MyContentProvider extends ContentProvider {
    public MyContentProvider() {
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // Implement this to handle requests to delete one or more rows.
        Log.v("MYTAG", "delete");
        return 0;
    }

    @Override
    public String getType(Uri uri) {
        Log.v("MYTAG", "getType");
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        Log.v("MYTAG", "insert...");
        return null;
    }

    @Override
    public boolean onCreate() {
        Log.v("MYTAG", "onCreate...");
        Log.v("MYTAG", "currThread:" + Thread.currentThread().getName());
        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        Log.v("MYTAG", "query...");
        Log.v("MYTAG", "currThread:" + Thread.currentThread().getName());
        return null;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        Log.v("MYTAG", "update...");
        return 0;
    }
}

為了測(cè)試方便,我們的方法只要調(diào)通即可局冰,所以相關(guān)方法了只是簡(jiǎn)單的打印了幾行日志测蘑,并沒有做具體的代碼邏輯實(shí)現(xiàn)。

注冊(cè)ContentProvider

定義完畢了ContentProvider康二,接下來的工作就是要在清單文件AndroidMnifest.xml里面進(jìn)行注冊(cè)碳胳,如下所示:

   <provider
            android:name=".provider.MyContentProvider"
            android:authorities="com.test.provider"
            android:process=":remote"
            android:enabled="true"
            android:exported="true"/>

通過name指定ContentProvider所在的路徑,authorities作為ContentProvider唯一的身份標(biāo)識(shí)沫勿,外界也就是通過它來訪問ContentProvider的挨约,process為ContentProvider指定所在的進(jìn)程,exported屬性表示是否允許外部應(yīng)用訪問,默認(rèn)為true产雹。這樣服務(wù)端的工作就做完了诫惭,現(xiàn)在我們看客戶端怎么來調(diào)用:

ContentProvider的調(diào)用
     Uri uri = Uri.parse("content://com.test.provider");
     getContentResolver().query(uri,null,null,null,null);
     getContentResolver().query(uri,null,null,null,null);
     getContentResolver().query(uri,null,null,null,null);

首先通過Uri對(duì)象的parse方法構(gòu)建了一個(gè)uri,這個(gè)參數(shù)就是我們?cè)贏ndroidMinifest.xml清單文件里面定義的authorities屬性的值蔓挖,然后我們以query方法為例調(diào)用了三次夕土,打印日志如下:

2019-11-21 10:49:19.148 4752-4764/? V/MYTAG: query...
2019-11-21 10:49:19.148 4752-4764/? V/MYTAG: currThread:Binder:4752_1
2019-11-21 10:49:19.150 4752-4766/? V/MYTAG: query...
2019-11-21 10:49:19.150 4752-4766/? V/MYTAG: currThread:Binder:4752_3
2019-11-21 10:49:19.150 4752-4766/? V/MYTAG: query...
2019-11-21 10:49:19.150 4752-4766/? V/MYTAG: currThread:Binder:4752_3

query方法響應(yīng)了,調(diào)用了三次瘟判,發(fā)現(xiàn)他們是在兩個(gè)線程中執(zhí)行的怨绣,說明服務(wù)器端是一個(gè)binder線程池,這一點(diǎn)需要注意一下荒适。

ConentProvider的注冊(cè)過程

以上就是整個(gè)ConentProvider的簡(jiǎn)單使用過程梨熙,接下來我們看看它的背后的工作原理。注冊(cè)首先是從ActivityThrad的main方法開始的刀诬,然后直到ConentProvider的onCreate方法被回調(diào)咽扇,此時(shí)就標(biāo)志整個(gè)注冊(cè)過程完成。接下來我們看ActivityThread的main方法:

public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

        // Install selective syscall interception
        AndroidOs.install();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");
        
        Looper.prepareMainLooper();

        // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
        // It will be in the format "seq=114"
        long startSeq = 0;
        if (args != null) {
            for (int i = args.length - 1; i >= 0; --i) {
                if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                    startSeq = Long.parseLong(
                            args[i].substring(PROC_START_SEQ_IDENT.length()));
                }
            }
        }
        //注釋1
        ActivityThread thread = new ActivityThread();
        //注釋2
        thread.attach(false, startSeq);

        if (sMainThreadHandler == null) {
            //注釋3
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

我們知道應(yīng)用程序所在的進(jìn)程被創(chuàng)建完畢陕壹,緊接著就會(huì)執(zhí)行ActivityThread的main方法初始化應(yīng)用质欲,在main方法里主要做了這么幾個(gè)工作,首先在注釋1處創(chuàng)建了一個(gè)ActivityThread 對(duì)象糠馆,然后在注釋2處掛載了應(yīng)用程序嘶伟,緊接著在注釋3處創(chuàng)建主線程的消息管理器。應(yīng)用程序的ContentProvider就是在ActivityThread的注釋2處的attach方法所初始化的又碌。該方法的實(shí)現(xiàn)如下所示:

  private void attach(boolean system, long startSeq) {
    ...
            android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                    UserHandle.myUserId());
            RuntimeInit.setApplicationObject(mAppThread.asBinder());
            final IActivityManager mgr = ActivityManager.getService();
            try {
                //初始1
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
    ...

這個(gè)方法有些長(zhǎng)九昧,我們只看關(guān)鍵部分绊袋,注釋1處它調(diào)用了ActivityManager.getService()對(duì)象的attachApplication方法,ActivityManager.getService在前面我們已經(jīng)多次提到過铸鹰,這不在重復(fù)解釋癌别,它就是ActivityManagerService,順藤摸瓜我們繼續(xù)往下走,ActivityManagerService的attachApplication方法如下所示:

ActivityManagerService中的流程
 @Override
    public final void attachApplication(IApplicationThread thread, long startSeq) {
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();
            final long origId = Binder.clearCallingIdentity();
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
            Binder.restoreCallingIdentity(origId);
        }
    }

ActivityManagerService的attachApplication方法幾乎什么都沒有做蹋笼,直接就把掛載app的工作交給了自己的attachApplicationLocked展姐,該方法如下所示:

  private final boolean attachApplicationLocked(IApplicationThread thread,
            int pid, int callingUid, long startSeq) {
  ...
  if (app.isolatedEntryPoint != null) {
                // This is an isolated process which should just call an entry point instead of
                // being bound to an application.
                thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
            } else if (instr2 != null) {
                //注釋1
                thread.bindApplication(processName, appInfo, providers,
                        instr2.mClass,
                        profilerInfo, instr2.mArguments,
                        instr2.mWatcher,
                        instr2.mUiAutomationConnection, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.isPersistent(),
                        new Configuration(app.getWindowProcessController().getConfiguration()),
                        app.compat, getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, autofillOptions, contentCaptureOptions);
            } else {
                thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
                        null, null, null, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.isPersistent(),
                        new Configuration(app.getWindowProcessController().getConfiguration()),
                        app.compat, getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, autofillOptions, contentCaptureOptions);
            }
            ...
            }

attachApplicationLocked這個(gè)方法還是比較長(zhǎng)的,我們直接看注釋1處剖毯,此時(shí)調(diào)用了ApplicationThread的bindApplication方法圾笨,該方法的實(shí)現(xiàn)如下:

ActivityThread中的流程

ApplicationThread的bindApplication方法的實(shí)現(xiàn)如下所示:

public final void bindApplication(String processName, ApplicationInfo appInfo,
                List<ProviderInfo> providers, ComponentName instrumentationName,
                ProfilerInfo profilerInfo, Bundle instrumentationArgs,
                IInstrumentationWatcher instrumentationWatcher,
                IUiAutomationConnection instrumentationUiConnection, int debugMode,
                boolean enableBinderTracking, boolean trackAllocation,
                boolean isRestrictedBackupMode, boolean persistent, Configuration config,
                CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
                String buildSerial, AutofillOptions autofillOptions,
                ContentCaptureOptions contentCaptureOptions) {
            if (services != null) {
                if (false) {
                    // Test code to make sure the app could see the passed-in services.
                    for (Object oname : services.keySet()) {
                        if (services.get(oname) == null) {
                            continue; // AM just passed in a null service.
                        }
                        String name = (String) oname;

                        // See b/79378449 about the following exemption.
                        switch (name) {
                            case "package":
                            case Context.WINDOW_SERVICE:
                                continue;
                        }

                        if (ServiceManager.getService(name) == null) {
                            Log.wtf(TAG, "Service " + name + " should be accessible by this app");
                        }
                    }
                }

                // Setup the service cache in the ServiceManager
                ServiceManager.initServiceCache(services);
            }

            setCoreSettings(coreSettings);

            AppBindData data = new AppBindData();
            data.processName = processName;
            data.appInfo = appInfo;
            data.providers = providers;
            data.instrumentationName = instrumentationName;
            data.instrumentationArgs = instrumentationArgs;
            data.instrumentationWatcher = instrumentationWatcher;
            data.instrumentationUiAutomationConnection = instrumentationUiConnection;
            data.debugMode = debugMode;
            data.enableBinderTracking = enableBinderTracking;
            data.trackAllocation = trackAllocation;
            data.restrictedBackupMode = isRestrictedBackupMode;
            data.persistent = persistent;
            data.config = config;
            data.compatInfo = compatInfo;
            data.initProfilerInfo = profilerInfo;
            data.buildSerial = buildSerial;
            data.autofillOptions = autofillOptions;
            data.contentCaptureOptions = contentCaptureOptions;
            sendMessage(H.BIND_APPLICATION, data);
        }

此時(shí)構(gòu)建了一個(gè)AppBindData并把它傳遞給了ActivityThread的消息管理器Handler了,收到消息后會(huì)調(diào)用ActivityThread的handleBindApplication方法逊谋,該方法的具體實(shí)現(xiàn)如下:

 private void handleBindApplication(AppBindData data) {
        ...
        Application app;
        final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
        final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
        try {
            // If the app is being launched for full backup or restore, bring it up in
            // a restricted environment with the base application class.
            //注釋1
            app = data.info.makeApplication(data.restrictedBackupMode, null);

            // Propagate autofill compat state
            app.setAutofillOptions(data.autofillOptions);

            // Propagate Content Capture options
            app.setContentCaptureOptions(data.contentCaptureOptions);

            mInitialApplication = app;

            // don't bring up providers in restricted mode; they may depend on the
            // app's custom Application class
            if (!data.restrictedBackupMode) {
                if (!ArrayUtils.isEmpty(data.providers)) {
                    //注釋2
                    installContentProviders(app, data.providers);
                }
            }

            // Do this after providers, since instrumentation tests generally start their
            // test thread at this point, and we don't want that racing.
            try {
                 mInstrumentation.onCreate(data.instrumentationArgs);
            }
            catch (Exception e) {
                throw new RuntimeException(
                    "Exception thrown in onCreate() of "
                    + data.instrumentationName + ": " + e.toString(), e);
            }
            try {
                //注釋3
                mInstrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                if (!mInstrumentation.onException(app, e)) {
                    throw new RuntimeException(
                      "Unable to create application " + app.getClass().getName()
                      + ": " + e.toString(), e);
                }
            }
            ...

handleBindApplication方法的實(shí)現(xiàn)有些長(zhǎng)擂达,我們只看關(guān)鍵部分,在注釋1處Application創(chuàng)建了涣狗,在注釋2處我們終于找到了初始化ContentProvider的真正方法installContentProviders谍婉,在注釋3處Application的onCreate被回調(diào)了,我們有沒有發(fā)現(xiàn)ContentProvider是先于Application初始化的镀钓,下面我主要看ContentProvider初始化的核心方法installContentProviders穗熬,該方法的具體實(shí)現(xiàn)如下:

 private void installContentProviders(
            Context context, List<ProviderInfo> providers) {
                     
        final ArrayList<ContentProviderHolder> results = new ArrayList<>();

        for (ProviderInfo cpi : providers) {
            if (DEBUG_PROVIDER) {
                StringBuilder buf = new StringBuilder(128);
                buf.append("Pub ");
                buf.append(cpi.authority);
                buf.append(": ");
                buf.append(cpi.name);
                Log.i(TAG, buf.toString());
            }
            //注釋1
            ContentProviderHolder cph = installProvider(context, null, cpi,
                    false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
            if (cph != null) {
                cph.noReleaseNeeded = true;
                results.add(cph);
            }
        }

        try {
            //注釋2
            ActivityManager.getService().publishContentProviders(
                getApplicationThread(), results);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }

installContentProviders方法的實(shí)現(xiàn)不是很復(fù)雜,就做了一件事就是初始化了一個(gè)ContentProviderHolder集合丁溅,并把它傳遞給服務(wù)端唤蔗,ContentProviderHolder具體是什么,我們主要看注釋1處的installProvider方法窟赏,該方法的具體實(shí)現(xiàn)如下:

 private ContentProviderHolder installProvider(Context context,
            ContentProviderHolder holder, ProviderInfo info,
            boolean noisy, boolean noReleaseNeeded, boolean stable) {
                ... 
                final java.lang.ClassLoader cl = c.getClassLoader();
                LoadedApk packageInfo = peekPackageInfo(ai.packageName, true);
                if (packageInfo == null) {
                    // System startup case.
                    packageInfo = getSystemContext().mPackageInfo;
                }
                //注釋1
                localProvider = packageInfo.getAppFactory()
                        .instantiateProvider(cl, info.name);
                //注釋2        
                provider = localProvider.getIContentProvider();
                if (provider == null) {
                    Slog.e(TAG, "Failed to instantiate class " +
                          info.name + " from sourceDir " +
                          info.applicationInfo.sourceDir);
                    return null;
                }
                if (DEBUG_PROVIDER) Slog.v(
                    TAG, "Instantiating local provider " + info.name);
                // XXX Need to create the correct context for this provider.
                //注釋3
                localProvider.attachInfo(c, info);
                ...
                if (localProvider != null) {
                ComponentName cname = new ComponentName(info.packageName, info.name);
                ProviderClientRecord pr = mLocalProvidersByName.get(cname);
                if (pr != null) {
                    if (DEBUG_PROVIDER) {
                        Slog.v(TAG, "installProvider: lost the race, "
                                + "using existing local provider");
                    }
                    provider = pr.mProvider;
                } else {
                    //注釋4
                    holder = new ContentProviderHolder(info);
                    //注釋5
                    holder.provider = provider;
                    holder.noReleaseNeeded = true;
                    pr = installProviderAuthoritiesLocked(provider, localProvider, holder);
                    mLocalProviders.put(jBinder, pr);
                    mLocalProvidersByName.put(cname, pr);
                }
                retHolder = pr.mHolder;
                }
                ...
                return retHolder;
  }

在注釋1處調(diào)用了packageInfo.getAppFactory()對(duì)象的instantiateProvider方法妓柜,我們看該方法的實(shí)現(xiàn):

    public @NonNull ContentProvider instantiateProvider(@NonNull ClassLoader cl,
            @NonNull String className)
            throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return (ContentProvider) cl.loadClass(className).newInstance();
    }

在instantiateProvider方法里ContentProvider終于通過反射實(shí)例化了。

在注釋2處調(diào)用了ContentProvider的getIContentProvider方法涯穷,我們看的具體實(shí)現(xiàn)是什么:

private Transport mTransport = new Transport();
public IContentProvider getIContentProvider() {
        return mTransport;
    }

返回了一個(gè)Transport對(duì)象棍掐,我們來看下它的實(shí)現(xiàn):

    class Transport extends ContentProviderNative {}    
    
    abstract public class ContentProviderNative extends Binder implements IContentProvider {}

通過繼承關(guān)系我們發(fā)現(xiàn)Transport繼承了ContentProviderNative ,而ContentProviderNative又繼承了Binder并實(shí)現(xiàn)了IContentProvider接口拷况,所以注釋2處的provider的實(shí)現(xiàn)就是Transport作煌,而它就是一個(gè)binder,這個(gè)binder會(huì)在注釋5處給他的ContentProviderHolder對(duì)象的provider屬性赚瘦, installProvider方法最后返回了持有ContentProvider的Binder對(duì)象的ContentProviderHolder粟誓。

然后我們?cè)诳醋⑨?處調(diào)用了ContentProvider的attachInfo方法,它的實(shí)現(xiàn)如下:

    public void attachInfo(Context context, ProviderInfo info) {
        attachInfo(context, info, false);
    }

    private void attachInfo(Context context, ProviderInfo info, boolean testing) {
        mNoPerms = testing;
        mCallingPackage = new ThreadLocal<>();

        /*
         * Only allow it to be set once, so after the content service gives
         * this to us clients can't change it.
         */
        if (mContext == null) {
            mContext = context;
            if (context != null && mTransport != null) {
                mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
                        Context.APP_OPS_SERVICE);
            }
            mMyUid = Process.myUid();
            if (info != null) {
                setReadPermission(info.readPermission);
                setWritePermission(info.writePermission);
                setPathPermissions(info.pathPermissions);
                mExported = info.exported;
                mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
                setAuthorities(info.authority);
            }   
            ContentProvider.this.onCreate();
        }
    }

兩個(gè)參數(shù)的attachInfo方法重載了三個(gè)參數(shù)的attachInfo方法起意,在該方法的最后一行鹰服,終于發(fā)現(xiàn)我們的ContentProvider的onCreate方法被調(diào)用了,這就意味著ContentProvider的啟動(dòng)已經(jīng)完成了。

現(xiàn)在我們?cè)倏磇nstallContentProviders方法的注釋2處調(diào)用了ActivityManager.getService()對(duì)象的publishContentProviders方法悲酷,并把客戶端生成的ContentProviderHolder對(duì)象傳遞給了服務(wù)端套菜。我們?cè)倏碅ctivityManagerService對(duì)象的publishContentProviders方法的具體實(shí)現(xiàn):

ActivityManagerService中的流程
 public final void publishContentProviders(IApplicationThread caller,
            List<ContentProviderHolder> providers) {
        if (providers == null) {
            return;
        }

        enforceNotIsolatedCaller("publishContentProviders");
        synchronized (this) {
            final ProcessRecord r = getRecordForAppLocked(caller);
            if (DEBUG_MU) Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
            if (r == null) {
                throw new SecurityException(
                        "Unable to find app for caller " + caller
                      + " (pid=" + Binder.getCallingPid()
                      + ") when publishing content providers");
            }

            final long origId = Binder.clearCallingIdentity();

            final int N = providers.size();
            for (int i = 0; i < N; i++) {
                ContentProviderHolder src = providers.get(i);
                if (src == null || src.info == null || src.provider == null) {
                    continue;
                }
                ContentProviderRecord dst = r.pubProviders.get(src.info.name);
                if (DEBUG_MU) Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
                if (dst != null) {
                    ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
                    mProviderMap.putProviderByClass(comp, dst);
                    String names[] = dst.info.authority.split(";");
                    for (int j = 0; j < names.length; j++) {
                        mProviderMap.putProviderByName(names[j], dst);
                    }

                    int launchingCount = mLaunchingProviders.size();
                    int j;
                    boolean wasInLaunchingProviders = false;
                    for (j = 0; j < launchingCount; j++) {
                        if (mLaunchingProviders.get(j) == dst) {
                            mLaunchingProviders.remove(j);
                            wasInLaunchingProviders = true;
                            j--;
                            launchingCount--;
                        }
                    }
                    if (wasInLaunchingProviders) {
                        mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, r);
                    }
                    // Make sure the package is associated with the process.
                    // XXX We shouldn't need to do this, since we have added the package
                    // when we generated the providers in generateApplicationProvidersLocked().
                    // But for some reason in some cases we get here with the package no longer
                    // added...  for now just patch it in to make things happy.
                    r.addPackage(dst.info.applicationInfo.packageName,
                            dst.info.applicationInfo.longVersionCode, mProcessStats);
                    synchronized (dst) {
                        dst.provider = src.provider;
                        dst.setProcess(r);
                        dst.notifyAll();
                    }
                    updateOomAdjLocked(r, true, OomAdjuster.OOM_ADJ_REASON_GET_PROVIDER);
                    maybeUpdateProviderUsageStatsLocked(r, src.info.packageName,
                            src.info.authority);
                }
            }

            Binder.restoreCallingIdentity(origId);
        }
    }

這個(gè)方法的主要作用就是把客戶端傳遞過來的ContentProviderHolder對(duì)象保存到了ContentProviderRecord對(duì)象。而通過上面的分析我們知道ContentProviderHolder里面存儲(chǔ)就是ContentProvider所對(duì)應(yīng)的Binder對(duì)象设易,所以其他應(yīng)用通過uri所查找的就是ActivityManagerService里面ContentProvider的Binder,拿到了Binder對(duì)象就可以遠(yuǎn)程調(diào)用ContentProvider里面的方法了笼踩。好了,截止目前ContentProvider的注冊(cè)就徹底講完了亡嫌,接下來我們看ConentResolver方法的調(diào)用。

ConentResolver的調(diào)用過程

ConentResolver中的流程

ConentProvider主要給我們提供了insert掘而,delete挟冠,update,query四個(gè)方法袍睡,我們以query方法為例進(jìn)行研究, 基本用法如下:

    Uri uri = Uri.parse("content://com.test.provider");
    getContentResolver().query(uri,null,null,null,null);

ContentWraper的getContentResolver方法實(shí)現(xiàn)如下:

  @Override
    public ContentResolver getContentResolver() {
        return mBase.getContentResolver();
    }

不用說了mBase就是ContentImpl知染,getContentResolver方法如下所示:

 private final ApplicationContentResolver mContentResolver;
 @Override
    public ContentResolver getContentResolver() {
        return mContentResolver;
    }

而mContentResolver就是一個(gè)ApplicationContentResolver,我們看看他的具體實(shí)現(xiàn):

private static final class ApplicationContentResolver extends ContentResolver {
        @UnsupportedAppUsage
        private final ActivityThread mMainThread;

        public ApplicationContentResolver(Context context, ActivityThread mainThread) {
            super(context);
            mMainThread = Preconditions.checkNotNull(mainThread);
        }

        @Override
        @UnsupportedAppUsage
        protected IContentProvider acquireProvider(Context context, String auth) {
            return mMainThread.acquireProvider(context,
                    ContentProvider.getAuthorityWithoutUserId(auth),
                    resolveUserIdFromAuthority(auth), true);
        }

        @Override
        protected IContentProvider acquireExistingProvider(Context context, String auth) {
            return mMainThread.acquireExistingProvider(context,
                    ContentProvider.getAuthorityWithoutUserId(auth),
                    resolveUserIdFromAuthority(auth), true);
        }

        @Override
        public boolean releaseProvider(IContentProvider provider) {
            return mMainThread.releaseProvider(provider, true);
        }

        @Override
        protected IContentProvider acquireUnstableProvider(Context c, String auth) {
            return mMainThread.acquireProvider(c,
                    ContentProvider.getAuthorityWithoutUserId(auth),
                    resolveUserIdFromAuthority(auth), false);
        }

        @Override
        public boolean releaseUnstableProvider(IContentProvider icp) {
            return mMainThread.releaseProvider(icp, false);
        }

        @Override
        public void unstableProviderDied(IContentProvider icp) {
            mMainThread.handleUnstableProviderDied(icp.asBinder(), true);
        }

        @Override
        public void appNotRespondingViaProvider(IContentProvider icp) {
            mMainThread.appNotRespondingViaProvider(icp.asBinder());
        }

        /** @hide */
        protected int resolveUserIdFromAuthority(String auth) {
            return ContentProvider.getUserIdFromAuthority(auth, getUserId());
        }
    }

ApplicationContentResolver是ContentResolver的一個(gè)具體實(shí)現(xiàn)類斑胜,它位于ContextImpl的內(nèi)部控淡。所以調(diào)用getContentResolver().query方法,其實(shí)就是調(diào)用了ApplicationContentResolver對(duì)象的query方法止潘,該方法的具體實(shí)現(xiàn)如下:

 public final @Nullable Cursor query(@RequiresPermission.Read @NonNull Uri uri,
            @Nullable String[] projection, @Nullable String selection,
            @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        return query(uri, projection, selection, selectionArgs, sortOrder, null);
    }
public final @Nullable Cursor query(@RequiresPermission.Read @NonNull Uri uri,
            @Nullable String[] projection, @Nullable String selection,
            @Nullable String[] selectionArgs, @Nullable String sortOrder,
            @Nullable CancellationSignal cancellationSignal) {
        Bundle queryArgs = createSqlQueryBundle(selection, selectionArgs, sortOrder);
        return query(uri, projection, queryArgs, cancellationSignal);
}
public final @Nullable Cursor query(final @RequiresPermission.Read @NonNull Uri uri,
            @Nullable String[] projection, @Nullable Bundle queryArgs,
            @Nullable CancellationSignal cancellationSignal) {
        Preconditions.checkNotNull(uri, "uri");

        try {
           if (mWrapped != null) {
                return mWrapped.query(uri, projection, queryArgs, cancellationSignal);
            }
        } catch (RemoteException e) {
            return null;
        }

        IContentProvider unstableProvider = acquireUnstableProvider(uri);
        if (unstableProvider == null) {
            return null;
        }
        IContentProvider stableProvider = null;
        Cursor qCursor = null;
        try {
            long startTime = SystemClock.uptimeMillis();

            ICancellationSignal remoteCancellationSignal = null;
            if (cancellationSignal != null) {
                cancellationSignal.throwIfCanceled();
                remoteCancellationSignal = unstableProvider.createCancellationSignal();
                cancellationSignal.setRemote(remoteCancellationSignal);
            }
            try {
                qCursor = unstableProvider.query(mPackageName, uri, projection,
                        queryArgs, remoteCancellationSignal);
            } catch (DeadObjectException e) {
                // The remote process has died...  but we only hold an unstable
                // reference though, so we might recover!!!  Let's try!!!!
                // This is exciting!!1!!1!!!!1
                unstableProviderDied(unstableProvider);
                //注釋1
                stableProvider = acquireProvider(uri);
                if (stableProvider == null) {
                    return null;
                }
                //注釋2
                qCursor = stableProvider.query(
                        mPackageName, uri, projection, queryArgs, remoteCancellationSignal);
            }
            if (qCursor == null) {
                return null;
            }

            // Force query execution.  Might fail and throw a runtime exception here.
            qCursor.getCount();
            long durationMillis = SystemClock.uptimeMillis() - startTime;
            maybeLogQueryToEventLog(durationMillis, uri, projection, queryArgs);

            // Wrap the cursor object into CursorWrapperInner object.
            final IContentProvider provider = (stableProvider != null) ? stableProvider
                    : acquireProvider(uri);
            final CursorWrapperInner wrapper = new CursorWrapperInner(qCursor, provider);
            stableProvider = null;
            qCursor = null;
            return wrapper;
        } catch (RemoteException e) {
            // Arbitrary and not worth documenting, as Activity
            // Manager will kill this process shortly anyway.
            return null;
        } finally {
            if (qCursor != null) {
                qCursor.close();
            }
            if (cancellationSignal != null) {
                cancellationSignal.setRemote(null);
            }
            if (unstableProvider != null) {
                releaseUnstableProvider(unstableProvider);
            }
            if (stableProvider != null) {
                releaseProvider(stableProvider);
            }
        }
    }

以上就是三個(gè)重載query的方法最終會(huì)調(diào)用最下面的這個(gè)query方法掺炭,首先我們看注釋1處的acquireProvider方法,該方法具體實(shí)現(xiàn)如下所示:

 @UnsupportedAppUsage
    public final IContentProvider acquireProvider(Uri uri) {
        if (!SCHEME_CONTENT.equals(uri.getScheme())) {
            return null;
        }
        final String auth = uri.getAuthority();
        if (auth != null) {
            return acquireProvider(mContext, auth);
        }
        return null;
    }
      protected IContentProvider acquireProvider(Context context, String auth) {
            //注釋1
            return mMainThread.acquireProvider(context,
                    ContentProvider.getAuthorityWithoutUserId(auth),
                    resolveUserIdFromAuthority(auth), true);
        }

ContentResolver最終會(huì)調(diào)用注釋1處的ActivityThrad的acquireProvider方法,該方法實(shí)現(xiàn)如下所示:

ActivityThrad中的流程
@UnsupportedAppUsage
    public final IContentProvider acquireProvider(
            Context c, String auth, int userId, boolean stable) {
        final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);
        //注釋1
        if (provider != null) {
            return provider;
        }

        // There is a possible race here.  Another thread may try to acquire
        // the same provider at the same time.  When this happens, we want to ensure
        // that the first one wins.
        // Note that we cannot hold the lock while acquiring and installing the
        // provider since it might take a long time to run and it could also potentially
        // be re-entrant in the case where the provider is in the same process.
        ContentProviderHolder holder = null;
        try {
            synchronized (getGetProviderLock(auth, userId)) {
                //注釋2
                holder = ActivityManager.getService().getContentProvider(
                        getApplicationThread(), c.getOpPackageName(), auth, userId, stable);
            }
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        if (holder == null) {
            Slog.e(TAG, "Failed to find provider info for " + auth);
            return null;
        }

        // Install provider will increment the reference count for us, and break
        // any ties in the race.
        holder = installProvider(c, holder, holder.info,
                true /*noisy*/, holder.noReleaseNeeded, stable);
        return holder.provider;
    }

在注釋1處如果能查詢到則直接就返回了凭戴,如果查詢不到會(huì)在服務(wù)端去查詢?cè)贑ontentProvider注冊(cè)的時(shí)候所在服務(wù)端ActivityManagerService中所保存的ContentProviderHolder 涧狮,而最終返回IContentProvider就是ContentProvider的對(duì)象Transport對(duì)象,最終調(diào)用的是Transport對(duì)象的query方法么夫,該方法的具體實(shí)現(xiàn)如下:

class Transport extends ContentProviderNative {
        volatile AppOpsManager mAppOpsManager = null;
        volatile int mReadOp = AppOpsManager.OP_NONE;
        volatile int mWriteOp = AppOpsManager.OP_NONE;
        //注釋1
        volatile ContentInterface mInterface = ContentProvider.this;

        ContentProvider getContentProvider() {
            return ContentProvider.this;
        }

        @Override
        public String getProviderName() {
            return getContentProvider().getClass().getName();
        }

        @Override
        public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
                @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
            uri = validateIncomingUri(uri);
            uri = maybeGetUriWithoutUserId(uri);
            if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
                // The caller has no access to the data, so return an empty cursor with
                // the columns in the requested order. The caller may ask for an invalid
                // column and we would not catch that but this is not a problem in practice.
                // We do not call ContentProvider#query with a modified where clause since
                // the implementation is not guaranteed to be backed by a SQL database, hence
                // it may not handle properly the tautology where clause we would have created.
                if (projection != null) {
                    return new MatrixCursor(projection, 0);
                }

                // Null projection means all columns but we have no idea which they are.
                // However, the caller may be expecting to access them my index. Hence,
                // we have to execute the query as if allowed to get a cursor with the
                // columns. We then use the column names to return an empty cursor.
                Cursor cursor;
                final String original = setCallingPackage(callingPkg);
                try {
                    //注釋2
                    cursor = mInterface.query(
                            uri, projection, queryArgs,
                            CancellationSignal.fromTransport(cancellationSignal));
                } catch (RemoteException e) {
                    throw e.rethrowAsRuntimeException();
                } finally {
                    setCallingPackage(original);
                }
                if (cursor == null) {
                    return null;
                }

                // Return an empty cursor for all columns.
                return new MatrixCursor(cursor.getColumnNames(), 0);
            }
            Trace.traceBegin(TRACE_TAG_DATABASE, "query");
            final String original = setCallingPackage(callingPkg);
            try {       
                return mInterface.query(
                        uri, projection, queryArgs,
                        CancellationSignal.fromTransport(cancellationSignal));
            } catch (RemoteException e) {
                throw e.rethrowAsRuntimeException();
            } finally {
                setCallingPackage(original);
                Trace.traceEnd(TRACE_TAG_DATABASE);
            }
        }
    ...

在Transport的query方法的注釋2處會(huì)調(diào)用mInterface對(duì)象的query方法者冤,而mInterface就是我們注釋1處的ContentProvider對(duì)象,此時(shí)ContentProvider對(duì)象的query方法就執(zhí)行了档痪,這就意味了ConentResolver的調(diào)用過程就徹底講完了涉枫。

總結(jié)

最后為了方便大家理解,我畫了兩幅流程圖腐螟。

ContentProvider注冊(cè)流程圖
在這里插入圖片描述

ActivityThread.main
ActivityThread.attach
ActivityManagerService.attachApplication
ActivityManagerService.attachApplicationLocked
ApplicationThread.bindApplication
ActivityThread.handleBindApplication
ActivityThread.installContentProviders
ActivityThread.installProvider
ContentProvider.attachInfo
ContentProvider.onCreate

ContentResolver調(diào)用流程圖
在這里插入圖片描述

ContentResolver.query
ApplicationContentResolver.query
ActivityThread.acquireProvider
ActivityManagerService.getContentProvider
Transport.query
ContentProvider.query

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末愿汰,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子遭垛,更是在濱河造成了極大的恐慌尼桶,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,376評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件锯仪,死亡現(xiàn)場(chǎng)離奇詭異泵督,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)庶喜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,126評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門小腊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來救鲤,“玉大人,你說我怎么就攤上這事秩冈”静” “怎么了?”我有些...
    開封第一講書人閱讀 156,966評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵入问,是天一觀的道長(zhǎng)丹锹。 經(jīng)常有香客問我,道長(zhǎng)芬失,這世上最難降的妖魔是什么楣黍? 我笑而不...
    開封第一講書人閱讀 56,432評(píng)論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮棱烂,結(jié)果婚禮上租漂,老公的妹妹穿的比我還像新娘。我一直安慰自己颊糜,他們只是感情好哩治,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,519評(píng)論 6 385
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著衬鱼,像睡著了一般业筏。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上鸟赫,一...
    開封第一講書人閱讀 49,792評(píng)論 1 290
  • 那天驾孔,我揣著相機(jī)與錄音,去河邊找鬼惯疙。 笑死翠勉,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的霉颠。 我是一名探鬼主播对碌,決...
    沈念sama閱讀 38,933評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼蒿偎!你這毒婦竟也來了朽们?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,701評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤诉位,失蹤者是張志新(化名)和其女友劉穎骑脱,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體苍糠,經(jīng)...
    沈念sama閱讀 44,143評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡叁丧,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,488評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拥娄。...
    茶點(diǎn)故事閱讀 38,626評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蚊锹,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出稚瘾,到底是詐尸還是另有隱情牡昆,我是刑警寧澤,帶...
    沈念sama閱讀 34,292評(píng)論 4 329
  • 正文 年R本政府宣布摊欠,位于F島的核電站锹安,受9級(jí)特大地震影響仪搔,放射性物質(zhì)發(fā)生泄漏脱茉。R本人自食惡果不足惜互艾,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,896評(píng)論 3 313
  • 文/蒙蒙 一刁赖、第九天 我趴在偏房一處隱蔽的房頂上張望焊刹。 院中可真熱鬧击罪,春花似錦芋簿、人聲如沸痒给。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,742評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽苍柏。三九已至尼斧,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間试吁,已是汗流浹背棺棵。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留熄捍,地道東北人烛恤。 一個(gè)月前我還...
    沈念sama閱讀 46,324評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像余耽,于是被迫代替她去往敵國和親缚柏。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,494評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容