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

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

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

ContentProvider的基本用法

定義ContentProvider

自定義一個ContentProvider很簡單,我只需要繼承ContentProvider,并復(fù)寫的它的增刪改查方法即可,具體代碼實現(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;
    }
}

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

注冊ContentProvider

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

   <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)識,外界也就是通過它來訪問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對象的parse方法構(gòu)建了一個uri,這個參數(shù)就是我們在AndroidMinifest.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)他們是在兩個線程中執(zhí)行的,說明服務(wù)器端是一個binder線程池,這一點需要注意一下。

ConentProvider的注冊過程

以上就是整個ConentProvider的簡單使用過程,接下來我們看看它的背后的工作原理。注冊首先是從ActivityThrad的main方法開始的,然后直到ConentProvider的onCreate方法被回調(diào),此時就標(biāo)志整個注冊過程完成。接下來我們看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)建完畢,緊接著就會執(zhí)行ActivityThread的main方法初始化應(yīng)用,在main方法里主要做了這么幾個工作,首先在注釋1處創(chuàng)建了一個ActivityThread 對象,然后在注釋2處掛載了應(yīng)用程序,緊接著在注釋3處創(chuàng)建主線程的消息管理器。應(yīng)用程序的ContentProvider就是在ActivityThread的注釋2處的attach方法所初始化的。該方法的實現(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();
            }
    ...

這個方法有些長,我們只看關(guān)鍵部分,注釋1處它調(diào)用了ActivityManager.getService()對象的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這個方法還是比較長的,我們直接看注釋1處,此時調(diào)用了ApplicationThread的bindApplication方法,該方法的實現(xiàn)如下:

ActivityThread中的流程

ApplicationThread的bindApplication方法的實現(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);
        }

此時構(gòu)建了一個AppBindData并把它傳遞給了ActivityThread的消息管理器Handler了,收到消息后會調(diào)用ActivityThread的handleBindApplication方法,該方法的具體實現(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方法的實現(xiàn)有些長,我們只看關(guān)鍵部分,在注釋1處Application創(chuàng)建了,在注釋2處我們終于找到了初始化ContentProvider的真正方法installContentProviders,在注釋3處Application的onCreate被回調(diào)了,我們有沒有發(fā)現(xiàn)ContentProvider是先于Application初始化的,下面我主要看ContentProvider初始化的核心方法installContentProviders,該方法的具體實現(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方法的實現(xiàn)不是很復(fù)雜,就做了一件事就是初始化了一個ContentProviderHolder集合,并把它傳遞給服務(wù)端,ContentProviderHolder具體是什么,我們主要看注釋1處的installProvider方法,該方法的具體實現(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()對象的instantiateProvider方法,我們看該方法的實現(xiàn):

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

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

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

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

返回了一個Transport對象,我們來看下它的實現(xiàn):

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

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

然后我們在看注釋3處調(diào)用了ContentProvider的attachInfo方法,它的實現(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();
        }
    }

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

現(xiàn)在我們再看installContentProviders方法的注釋2處調(diào)用了ActivityManager.getService()對象的publishContentProviders方法,并把客戶端生成的ContentProviderHolder對象傳遞給了服務(wù)端。我們再看ActivityManagerService對象的publishContentProviders方法的具體實現(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);
        }
    }

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

ConentResolver的調(diào)用過程

ConentResolver中的流程

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

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

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

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

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

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

而mContentResolver就是一個ApplicationContentResolver,我們看看他的具體實現(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的一個具體實現(xiàn)類,它位于ContextImpl的內(nèi)部。所以調(diào)用getContentResolver().query方法,其實就是調(diào)用了ApplicationContentResolver對象的query方法,該方法的具體實現(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);
            }
        }
    }

以上就是三個重載query的方法最終會調(diào)用最下面的這個query方法,首先我們看注釋1處的acquireProvider方法,該方法具體實現(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最終會調(diào)用注釋1處的ActivityThrad的acquireProvider方法,該方法實現(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處如果能查詢到則直接就返回了,如果查詢不到會在服務(wù)端去查詢在ContentProvider注冊的時候所在服務(wù)端ActivityManagerService中所保存的ContentProviderHolder ,而最終返回IContentProvider就是ContentProvider的對象Transport對象,最終調(diào)用的是Transport對象的query方法,該方法的具體實現(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處會調(diào)用mInterface對象的query方法,而mInterface就是我們注釋1處的ContentProvider對象,此時ContentProvider對象的query方法就執(zhí)行了,這就意味了ConentResolver的調(diào)用過程就徹底講完了。

總結(jié)

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

ContentProvider注冊流程圖
在這里插入圖片描述

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)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容