美文网首页
Android源码学习-ContentProvider工作流程浅

Android源码学习-ContentProvider工作流程浅

作者: m1Ku | 来源:发表于2019-07-10 17:58 被阅读0次

    介绍

    ContentProvider作为四大组件之一,它可以为其他组件或者其他应用提供数据。它会在进程启动时同时启动并发布到AMS中,现在通过源码来学习了解相关流程。

    //BookProvider 继承自ContentProvider
    Uri uri = Uri.parse("content://com.m1ku.testproject.provider.BookProvider");
    getContentResolver().query(uri, null, null, null, null);
    

    源码分析

    从query方法作为入口切入源码

    首先通过getContentResolver()获取ContentResolver对象

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

    调用ContextImpl的方法

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

    ContentResolver是一个抽象类,这里返回它的实现ApplicationContentResolver对象,该对象在ContextImpl构造时初始化。

    调用ContentResolver的query方法

    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) {
      //...
      IContentProvider unstableProvider = acquireUnstableProvider(uri);
      //...
    }
    

    调用ApplicationContentResolver的acquireUnstableProvider

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

    调用ActivityThread的acquireProvider

    public final IContentProvider acquireProvider(
            Context c, String auth, int userId, boolean stable) {
        final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);
        if (provider != null) {
            return provider;
        }
        ContentProviderHolder holder = null;
        try {
            holder = ActivityManager.getService().getContentProvider(
                    getApplicationThread(), auth, userId, stable);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        holder = installProvider(c, holder, holder.info,
                true /*noisy*/, holder.noReleaseNeeded, stable);
        return holder.provider;
    }
    

    首先会查询该ContentProvider是否存在,如果存在的话直接将其返回。否则远程调用AMS的getContentProvider方法

    @Override
    public final ContentProviderHolder getContentProvider(
            IApplicationThread caller, String name, int userId, boolean stable) {
        //...
        return getContentProviderImpl(caller, name, null, stable, userId);
    }
    
    private ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
                                                         String name, IBinder token, boolean stable, int userId) {
      //...
       ProcessRecord proc = getProcessRecordLocked(
                                    cpi.processName, cpr.appInfo.uid, false);
                            if (proc != null && proc.thread != null && !proc.killed) {
                                if (!proc.pubProviders.containsKey(cpi.name)) {
                                                                proc.pubProviders.put(cpi.name, cpr);
                                    try {
                                        proc.thread.scheduleInstallProvider(cpi);
                                    } catch (RemoteException e) {
                                    }
                                }
                            } else {
                                proc = startProcessLocked(cpi.processName,
                                        cpr.appInfo, false, 0, "content provider",
                                        new ComponentName(cpi.applicationInfo.packageName,
                                                cpi.name), false, false, false);
                            }
                            cpr.launchingApp = proc;
                            mLaunchingProviders.add(cpr);
      //...
    }
    

    如果ContentProvider所在的进程还未启动的话,会调用startProcessLocked启动该进程,该方法的调用栈中最终会调用Process.start方法启动进程,新进程启动后入口方法就是ActivityThread的main方法

    public static void main(String[] args) {
      Looper.prepareMainLooper();
    
      ActivityThread thread = new ActivityThread();
      thread.attach(false);
    
      if (sMainThreadHandler == null) {
          sMainThreadHandler = thread.getHandler();
       }
       Looper.loop();
    }
    

    在main方法中,首先初始化了ActivityThread对象,并调用其attach方法,最后开启了主线程的消息循环。

    private void attach(boolean system) {
      //...
          final IActivityManager mgr = ActivityManager.getService();
          try {
               mgr.attachApplication(mAppThread);
          } catch (RemoteException ex) {
               throw ex.rethrowFromSystemServer();
          }
      //...
    }
    

    attach方法中远程调用AMS的attachApplication方法将ApplicationThread传入到AMS中

    @Override
    public final void attachApplication(IApplicationThread thread) {
        synchronized (this) {
            //...
            attachApplicationLocked(thread, callingPid);
                //...
        }
    }
    
    private final boolean attachApplicationLocked(IApplicationThread thread,
                                                  int pid) {
      //...
      thread.bindApplication(processName, appInfo, providers,
                            app.instr.mClass,
                            profilerInfo, app.instr.mArguments,
                            app.instr.mWatcher,
                            app.instr.mUiAutomationConnection, testMode,
                            mBinderTransactionTrackingEnabled, enableTrackAllocation,
                            isRestrictedBackupMode || !normalMode, app.persistent,
                            new Configuration(getGlobalConfiguration()), app.compat,
                            getCommonServicesLocked(app.isolated),
                            mCoreSettingsObserver.getCoreSettingsLocked(),
                            buildSerial);
      //...
    }
    

    调用ApplicationThread的bindApplication方法,在该方法中发送了一个H.BIND_APPLICATION类型的消息,该消息的处理方法为

    private void handleBindApplication(AppBindData data) {
      //...
      final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
      //...
      final ClassLoader cl = instrContext.getClassLoader();
      mInstrumentation = (Instrumentation)
                        cl.loadClass(data.instrumentationName.getClassName()).newInstance();
      //...
      Application app = data.info.makeApplication(data.restrictedBackupMode, null);
      mInitialApplication = app;
      //...
      if (!data.restrictedBackupMode) {
              if (!ArrayUtils.isEmpty(data.providers)) {
                  installContentProviders(app, data.providers);
                  mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
                 }
          }
       //...
       mInstrumentation.callApplicationOnCreate(app);
    }
    

    首先创建了ContextImpl对象,然后用类加载器创建了Instrumentation对象,调用makeApplication

    public Application makeApplication(boolean forceDefaultAppClass,
                                       Instrumentation instrumentation) {
      //...
      ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
      app = mActivityThread.mInstrumentation.newApplication(
                        cl, appClass, appContext);
      appContext.setOuterContext(app);
      //...
    
    }
    

    调用newApplication完成了Application对象的创建。在完成Application的创建后,会调用installContentProviders初始化该进程中的ContentProvider

    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());
            }
            ContentProviderHolder cph = installProvider(context, null, cpi,
                    false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
            if (cph != null) {
                cph.noReleaseNeeded = true;
                results.add(cph);
            }
        }
    
        try {
            ActivityManager.getService().publishContentProviders(
                getApplicationThread(), results);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }
    

    遍历providers,调用installProvider方法

    private ContentProviderHolder installProvider(Context context,
            ContentProviderHolder holder, ProviderInfo info,
                                                  boolean noisy, boolean noReleaseNeeded, boolean stable) {
      //...
       final java.lang.ClassLoader cl = c.getClassLoader();
       localProvider = (ContentProvider)cl.loadClass(info.name).newInstance();
      //...
       localProvider.attachInfo(c, info);
    }
    

    这里通过类加载器构建了ContentProvider对象,然后调用attachInfo方法,其中回调了ContentProvider的onCreate方法,由于该方法是由主线程mH Handler执行的,所以onCreate回调在主线程中。最后远程调用AMS的publishContentProviders方法将他们保存在AMS中。ContentProvider完成创建后,在handleBindApplication中又回调了Application的onCreate方法,所以这里ContentProvider的onCreate是先于Application的onCreate方法调用的。

    调用query方法查询时,我们通过acquireUnstableProvider获得的是IContentProvider这个Binder接口,而它的实现是ContentProviderNative和ContentProvider.Transport,Transport对象继承自ContentProviderNative,那么这里就是调用的Transport的query方法。这里是通过Binder来调用的,外界无法访问直接访问ContentProvider,它只能通过AMS根据Uri来获取对应的ContentProvider的Binder接口,再通过IContentProvider来访问ContentProvider中的数据源。

    @Override
    public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
                        @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
      //...
      Cursor cursor = ContentProvider.this.query(
                            uri, projection, queryArgs,
                            CancellationSignal.fromTransport(cancellationSignal));
      //...
    }
    

    最后就调用到了ContentProvider的query方法,这个query方法执行在Binder线程中,方法的执行结果会通过Binder返回给调用者。这里以query方法为例分析了ContentProvider的工作流程,而其他几个方法也是类似的。

    相关文章

      网友评论

          本文标题:Android源码学习-ContentProvider工作流程浅

          本文链接:https://www.haomeiwen.com/subject/dghkkctx.html