Android中级——四大组件工作过程

四大组件工作过程

Activity

startActivity()最终都会调用到startActivityForResult()

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
    if (mParent == null) {
        options = transferSpringboardActivityOptions(options);
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        if (ar != null) {
            mMainThread.sendActivityResult(
                mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                ar.getResultData());
        }
        if (requestCode >= 0) {
           
            mStartedActivity = true;
        }
        cancelInputsAndStartExitTransition(options);
       
    }......
}

上面调用Instrumentation的execStartActivity()

public ActivityResult execStartActivity(......) {
   	......
    try {
        ......
        int result = ActivityTaskManager.getService().startActivity(whoThread,
                who.getBasePackageName(), who.getAttributionTag(), intent,
                intent.resolveTypeIfNeeded(who.getContentResolver()), token,
                target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}

上面获取ActivityTaskManagerService,是IPC过程,调用其startActivity()启动,然后调到startActivityAsUser()

private int startActivityAsUser(......) {
    ......
    return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
            .setCaller(caller)
            .setCallingPackage(callingPackage)
            .setCallingFeatureId(callingFeatureId)
            .setResolvedType(resolvedType)
            .setResultTo(resultTo)
            .setResultWho(resultWho)
            .setRequestCode(requestCode)
            .setStartFlags(startFlags)
            .setProfilerInfo(profilerInfo)
            .setActivityOptions(bOptions)
            .setUserId(userId)
            .execute();
}

上面通过ActivityStartController获取ActivityStarter

  • 调用 ActivityStarter 的 execute()、executeRequest()、startActivityUnchecked()、startActivityInner()
  • 调用 ActivityStack 的 startActivityLocked() 、positionChildAtTop()、positionChildAt()
  • 调用 RootWindowContainer 的 resumeFocusedStacksTopActivities()
  • 调用 ActivityStack 的 resumeTopActivityUncheckedLocked()、resumeTopActivityInnerLocked()
  • 调用 ActivityStackSupervisor 的 startSpecificActivity()realStartActivityLocked()
  • 调用 ClientLifecycleManager 的 scheduleTransaction()
  • 调用 ClientTransaction 的 schedule()
  • 调用 ActivityThread 中 ApplicationThread 的 scheduleTransaction()
  • 调用 ClientTransactionHandler 的 scheduleTransaction()
  • 调用 ClientTransaction() 的 preExecute()
  • 向 ActivityThread 发送 H.EXECUTE_TRANSACTION
  • 调用 TransactionExecutor 的 execute()、executeCallbacks()、cycleToPath()、performLifecycleSequence()
  • 调用 ClientTransactionHandler 子类 ActivityThread 的handleLaunchActivity()performLaunchActivity()

下面主要分析performLaunchActivity(),首先从ActivityClientRecord获取Activity的信息,创建ContextImpl,其是Context的具体实现

ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
    r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
            Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
    component = r.intent.resolveActivity(
            mInitialApplication.getPackageManager());
    r.intent.setComponent(component);
}
if (r.activityInfo.targetActivity != null) {
    component = new ComponentName(r.activityInfo.packageName,
            r.activityInfo.targetActivity);
}
ContextImpl appContext = createBaseContextForActivity(r);

通过Instrumentation的newActivity()使用ClassLoader创建Activity,返回 (Activity) cl.loadClass(className).newInstance();

try {
    java.lang.ClassLoader cl = appContext.getClassLoader();
    activity = mInstrumentation.newActivity(
            cl, component.getClassName(), r.intent);
    StrictMode.incrementExpectedActivityCount(activity.getClass());
    r.intent.setExtrasClassLoader(cl);
    r.intent.prepareToEnterProcess();
    if (r.state != null) {
        r.state.setClassLoader(cl);
    }
}......

通过LoadedApk的makeApplication()创建Application

  • 若已创建则不再创建

  • Instrumentation的newApplication() 返回 (Application) cl.loadClass(className).newInstance();

  • Instrumentation的callApplicationOnCreate() 调用onCreate()方法

    @UnsupportedAppUsage
    public Application makeApplication(boolean forceDefaultAppClass,
    Instrumentation instrumentation) {
    if (mApplication != null) {
    return mApplication;
    }
    Application app = null;
    String appClass = mApplicationInfo.className;
    if (forceDefaultAppClass || (appClass == null)) {
    appClass = "android.app.Application";
    }
    try {
    final java.lang.ClassLoader cl = getClassLoader();
    if (!mPackageName.equals("android")) {
    initializeJavaContextClassLoader();
    }

          SparseArray<String> packageIdentifiers = getAssets().getAssignedPackageIdentifie
                  false, false);
          for (int i = 0, n = packageIdentifiers.size(); i < n; i++) {
              final int id = packageIdentifiers.keyAt(i);
              if (id == 0x01 || id == 0x7f) {
                  continue;
              }
              rewriteRValues(cl, packageIdentifiers.valueAt(i), id);
          }
          ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
          NetworkSecurityConfigProvider.handleNewApplication(appContext);
          app = mActivityThread.mInstrumentation.newApplication(
                  cl, appClass, appContext);
          appContext.setOuterContext(app);
      }......
      mActivityThread.mAllApplications.add(app);
      mApplication = app;
      if (instrumentation != null) {
          try {
              instrumentation.callApplicationOnCreate(app);
          }......
      }
      ......
      return app;
    

    }

通过Activity的attach初始化数据,包括和ContextImpl建立关联、创建Window及关联

CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (r.overrideConfig != null) {
    config.updateFrom(r.overrideConfig);
}

Window window = null;
if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
    window = r.mPendingRemoveWindow;
    r.mPendingRemoveWindow = null;
    r.mPendingRemoveWindowManager = null;
}

appContext.getResources().addLoaders(
        app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
appContext.setOuterContext(activity);
activity.attach(appContext, this, getInstrumentation(), r.token,
        r.ident, app, r.intent, r.activityInfo, title, r.parent,
        r.embeddedID, r.lastNonConfigurationInstances, config,
        r.referrer, r.voiceInteractor, window, r.configCallback,
        r.assistToken);

通过Instrumentation的callActivityOnCreate调用onCreate(),至此Activity启动完成

Service

startService()过程

会调用到ContextWrapper的startService(),mBase为ContextImpl

@Override
public ComponentName startService(Intent service) {
    return mBase.startService(service);
}

会调用到ContextImpl的startServiceCommon()

private ComponentName startServiceCommon(Intent service, boolean requireForeground,
                                         UserHandle user) {
    try {
        validateServiceIntent(service);
        service.prepareToLeaveProcess(this);
        ComponentName cn = ActivityManager.getService().startService(
                mMainThread.getApplicationThread(), service,
                service.resolveTypeIfNeeded(getContentResolver()), requireForeground,
                getOpPackageName(), getAttributionTag(), user.getIdentifier());
        ......
        return cn;
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}

会调用到ActivityManagerService的startService()

@Override
public ComponentName startService(......)  throws TransactionTooLargeException {
	......
    synchronized (this) {
        final int callingPid = Binder.getCallingPid();
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        ComponentName res;
        try {
            res = mServices.startServiceLocked(caller, service,
                    resolvedType, callingPid, callingUid,
                    requireForeground, callingPackage, callingFeatureId, userId);
        } finally {
            Binder.restoreCallingIdentity(origId);
        }
        return res;
    }
}

会调用

  • ActiveServices 的 startServiceLocked()、startServiceInnerLocked()、bringUpServiceLocked()、realStartServiceLocked()、sendServiceArgsLocked()这里会调用onStartCommand()
  • ActivityThread 中 ApplicationThread 的 scheduleCreateService()、发送H.CREATE_SERVICE、handleCreateService()

主要分析handleCreateService()

  • 创建ContextImpl、Application、Service

  • 调用attach,建立ContextImpl和Service的联系

  • 调用onCreate(),将service放到mServices列表

    private void handleCreateService(CreateServiceData data) {
    unscheduleGcIdler();
    LoadedApk packageInfo = getPackageInfoNoCheck(
    data.info.applicationInfo, data.compatInfo);
    Service service = null;
    try {
    ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
    Application app = packageInfo.makeApplication(false, mInstrumentation);
    java.lang.ClassLoader cl = packageInfo.getClassLoader();
    service = packageInfo.getAppFactory()
    .instantiateService(cl, data.info.name, data.intent);
    context.getResources().addLoaders(
    app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
    context.setOuterContext(service);
    service.attach(context, this, data.info.name, data.token, app,
    ActivityManager.getService());
    service.onCreate();
    mServices.put(data.token, service);
    try {
    ActivityManager.getService().serviceDoneExecuting(
    data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
    } catch (RemoteException e) {
    throw e.rethrowFromSystemServer();
    }
    }......
    }

bindService()过程

会调用到ContextWrapper的bindService(),mBase为ContextImpl

@Override
public boolean bindService(Intent service, ServiceConnection conn,
        int flags) {
    return mBase.bindService(service, conn, flags);
}

上面调用到ContextImpl的bindServiceCommon()

@Override
public boolean bindService(Intent service, ServiceConnection conn, int flags) {
    warnIfCallingFromSystemProcess();
    return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null,
            getUser());
}

private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
            String instanceName, Handler handler, Executor executor, UserHandle user) {
    IServiceConnection sd;
    ......
    if (mPackageInfo != null) {
        if (executor != null) {
            sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags);
        } else {
            sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
        }
    }......
    validateServiceIntent(service);
    try {
        IBinder token = getActivityToken();
        if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
                && mPackageInfo.getApplicationInfo().targetSdkVersion
                < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            flags |= BIND_WAIVE_PRIORITY;
        }
        service.prepareToLeaveProcess(this);
        int res = ActivityManager.getService().bindIsolatedService(
                mMainThread.getApplicationThread(), getActivityToken(), service,
                service.resolveTypeIfNeeded(getContentResolver()),
                sd, flags, instanceName, getOpPackageName(), user.getIdentifier());
        ......
        return res != 0;
    }......
}

上面调用到LoadedApk的getServiceDispatcher()、getServiceDispatcherCommon()

  • 先查找是否存在当前ServiceConnection所对应的ServiceDispatcher,不存在则创建并存在mServices中

  • 将ServiceConnection转为ServiceDispatcher.InnerConnection对象(充当Binder),因为绑定服务可能是跨进程的

    private IServiceConnection getServiceDispatcherCommon(ServiceConnection c,
    Context context, Handler handler, Executor executor, int flags) {
    synchronized (mServices) {
    LoadedApk.ServiceDispatcher sd = null;
    ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map = mServices.get(context);
    if (map != null) {
    sd = map.get(c);
    }
    if (sd == null) {
    if (executor != null) {
    sd = new ServiceDispatcher(c, context, executor, flags);
    } else {
    sd = new ServiceDispatcher(c, context, handler, flags);
    }

              if (map == null) {
                  map = new ArrayMap<>();
                  mServices.put(context, map);
              }
              map.put(c, sd);
          } else {
              sd.validate(context, handler, executor);
          }
          return sd.getIServiceConnection();
      }
    

    }

接下来调用

  • ActivityManagerService 的 bindIsolatedService()
  • ActiveServices 的 bindServiceLocked()、bringUpServiceLocked()、realStartServiceLocked()
  • ActivityThread 中 ApplicationThread 的 scheduleCreateService()创建Service,同上
  • ActiveServices 的 requestServiceBindingsLocked()、requestServiceBindingLocked()
  • ActivityThread 中 ApplicationThread 的 scheduleBindService()、发送H.BIND_SERVICE、handleBindService()

主要分析handleBindService(),从mServices取出Service,调用onBind()获取服务端Binder,此时已经绑定成功

private void handleBindService(BindServiceData data) {
    Service s = mServices.get(data.token);
    ......
    if (s != null) {
        try {
            data.intent.setExtrasClassLoader(s.getClassLoader());
            data.intent.prepareToEnterProcess();
            try {
                if (!data.rebind) {
                    IBinder binder = s.onBind(data.intent);
                    ActivityManager.getService().publishService(
                            data.token, data.intent, binder);
                } else {
                    s.onRebind(data.intent);
                    ActivityManager.getService().serviceDoneExecuting(
                            data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
                }
            }......
        }......
    }
}

接下来调用

  • ActivityManagerService() 的 publishService()
  • ActiveServices 的 publishServiceLocked()
  • ConnectionRecord 中 ServiceDispatcher.InnerConnection 的 connected(),传入onBind()获取的服务端Binder
  • LoadedApk 中 ServiceDispatcher 的 connected()

mActivityThread等于调用ContextImpl的bindService()时传入的mMainThread.getHandler(),故RunConnection会运行在主线程中

public void connected(ComponentName name, IBinder service, boolean dead) {
    if (mActivityExecutor != null) {
        mActivityExecutor.execute(new RunConnection(name, service, 0, dead));
    } else if (mActivityThread != null) {
        mActivityThread.post(new RunConnection(name, service, 0, dead));
    } else {
        doConnected(name, service, dead);
    }
}

调用LoadedApk 中 ServiceDispatcher 的 doConnected()

private final class RunConnection implements Runnable {
    RunConnection(ComponentName name, IBinder service, int command, boolean dead) {
        mName = name;
        mService = service;
        mCommand = command;
        mDead = dead;
    }
    public void run() {
        if (mCommand == 0) {
            doConnected(mName, mService, mDead);
        } else if (mCommand == 1) {
            doDeath(mName, mService);
        }
    }
    final ComponentName mName;
    final IBinder mService;
    final int mCommand;
    final boolean mDead;
}

doConnected()会调用onServiceConnected(),并将服务端Binder传回客户端

public void doConnected(ComponentName name, IBinder service, boolean dead) {
    ServiceDispatcher.ConnectionInfo old;
    ServiceDispatcher.ConnectionInfo info;
    synchronized (this) {
        if (mForgotten) {
            return;
        }
        old = mActiveConnections.get(name);
        if (old != null && old.binder == service) {
            return;
        }
        if (service != null) {
            info = new ConnectionInfo();
            info.binder = service;
            info.deathMonitor = new DeathMonitor(name, service);
            try {
                service.linkToDeath(info.deathMonitor, 0);
                mActiveConnections.put(name, info);
            } catch (RemoteException e) {
                mActiveConnections.remove(name);
                return;
            }
        } else {
            mActiveConnections.remove(name);
        }
        if (old != null) {
            old.binder.unlinkToDeath(old.deathMonitor, 0);
        }
    }
    if (old != null) {
        mConnection.onServiceDisconnected(name);
    }
    if (dead) {
        mConnection.onBindingDied(name);
    }
    if (service != null) {
        mConnection.onServiceConnected(name, service);
    } else {
        mConnection.onNullBinding(name);
    }
}

BroadcastReceiver

注册过程

静态注册在应用安装时由PackageManagerService完成注册,动态注册从ContextWrapper的registerReceiver()开始,mBase为ContextImpl

@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
    return mBase.registerReceiver(receiver, filter);
}

上面调用到ContextImpl的registerReceiverInternal()

  • 将BroadcastReceiver转为LoadedApk.ReceiverDispatcher中的InnerReceiver(充当Binder),因为注册可能是跨进程的

    private Intent registerReceiverInternal(BroadcastReceiver receiver, int userId,
    IntentFilter filter, String broadcastPermission,
    Handler scheduler, Context context, int flags) {
    IIntentReceiver rd = null;
    if (receiver != null) {
    if (mPackageInfo != null && context != null) {
    if (scheduler == null) {
    scheduler = mMainThread.getHandler();
    }
    rd = mPackageInfo.getReceiverDispatcher(
    receiver, context, scheduler,
    mMainThread.getInstrumentation(), true);
    } else {
    if (scheduler == null) {
    scheduler = mMainThread.getHandler();
    }
    rd = new LoadedApk.ReceiverDispatcher(
    receiver, context, scheduler, null, true).getIIntentReceiver();
    }
    }
    try {
    final Intent intent = ActivityManager.getService().registerReceiverWithFeature(
    mMainThread.getApplicationThread(), mBasePackageName, getAttributionTag(), r
    filter, broadcastPermission, userId, flags);
    if (intent != null) {
    intent.setExtrasClassLoader(getClassLoader());
    intent.prepareToEnterProcess();
    }
    return intent;
    } catch (RemoteException e) {
    throw e.rethrowFromSystemServer();
    }
    }

上面调用到ActivityManagerService的registerReceiverWithFeature(),将InnerReceiver和IntentFilter存储起来

public Intent registerReceiverWithFeature(IApplicationThread caller, String callerPackage,
                                          String callerFeatureId, IIntentReceiver receiver, 
                                          String permission, int userId, int flags) {
    ......
    synchronized (this) {
        ......
        ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
        if (rl == null) {
            rl = new ReceiverList(this, callerApp, callingPid, callingUid,
                    userId, receiver);
            if (rl.app != null) {
                final int totalReceiversForApp = rl.app.receivers.size();
                rl.app.receivers.add(rl);
            } else {
                try {
                    receiver.asBinder().linkToDeath(rl, 0);
                } catch (RemoteException e) {
                    return sticky;
                }
                rl.linkedToDeath = true;
            }
            mRegisteredReceivers.put(receiver.asBinder(), rl);
        }......
        BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, callerFeatureId,
                permission, callingUid, userId, instantApp, visibleToInstantApps);
        if (rl.containsFilter(filter)) {
            ......
        } else {
            rl.add(bf);
            ......
            mReceiverResolver.addFilter(bf);
        }
        ......
    }
}

发送和接收过程

ContextWrapper的sendBroadcast()开始,mBase为ContextImpl

@Override
public void sendBroadcast(Intent intent) {
    mBase.sendBroadcast(intent);
}

上面调用ContextImpl的sendBroadcast()

@Override
public void sendBroadcast(Intent intent) {
    warnIfCallingFromSystemProcess();
    String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
    try {
        intent.prepareToLeaveProcess(this);
        ActivityManager.getService().broadcastIntentWithFeature(
                mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
                null, Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false,
                false, getUserId());
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}

上面调用ActivityManagerService的broadcastIntentWithFeature()、broadcastIntentLocked()

  • FLAG_EXCLUDE_STOPPED_PACKAGES表示不会向已停止的app发送广播

  • 根据intent-filter查找匹配的BroadcastReceiver,并添加到BroadcastQueue

    final int broadcastIntentLocked(ProcessRecord callerApp, String callerPackage,
    @Nullable String callerFeatureId, Intent intent, String resolvedType,
    IIntentReceiver resultTo, int resultCode, String resultData,
    Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions,
    boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid,
    int realCallingPid, int userId, boolean allowBackgroundActivityStarts,
    @Nullable int[] broadcastWhitelist) {
    intent = new Intent(intent);
    ......
    intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
    ......
    final BroadcastQueue queue = broadcastQueueForIntent(intent);
    BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage,
    callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
    requiredPermissions, appOp, brOptions, registeredReceivers, resultTo,
    resultCode, resultData, resultExtras, ordered, sticky, false, userId,
    allowBackgroundActivityStarts, timeoutExempt);
    final boolean replaced = replacePending
    && (queue.replaceParallelBroadcastLocked(r) != null);
    if (!replaced) {
    queue.enqueueParallelBroadcastLocked(r);
    queue.scheduleBroadcastsLocked();
    }
    }

上面再调用

  • BroadcastQueue的scheduleBroadcastsLocked()、发送BROADCAST_INTENT_MSG、processNextBroadcast()、processNextBroadcastLocked()、deliverToRegisteredReceiverLocked()、performReceiveLocked()

  • ActivityThread 中 ApplicationThread 的 scheduleRegisteredReceiver()

  • LoadedApk.ReceiverDispatcher中InnerReceiver的performReceive()

  • LoadedApk.ReceiverDispatcher的performReceive()

    public void performReceive(Intent intent, int resultCode, String data,
    Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
    final Args args = new Args(intent, resultCode, data, extras, ordered,
    sticky, sendingUser);
    ......
    if (intent == null || !mActivityThread.post(args.getRunnable())) {
    if (mRegistered && ordered) {
    IActivityManager mgr = ActivityManager.getService();
    args.sendFinished(mgr);
    }
    }
    }

mActivityThread等于调用ContextImpl的sendBroadcast()时传入的mMainThread.getHandler(),故Args会运行在主线程中,回调onReceive(),此时应用已接收到广播

final class Args extends BroadcastReceiver.PendingResult {
    ......
    public final Runnable getRunnable() {
        return () -> {
            .....
            try {
                ClassLoader cl = mReceiver.getClass().getClassLoader();
                intent.setExtrasClassLoader(cl);
                intent.prepareToEnterProcess();
                setExtrasClassLoader(cl);
                receiver.setPendingResult(this);
                receiver.onReceive(mContext, intent);
            }......
        };
    }
}

ContentProvider

以query()为例,调用ContentResolver的acquireUnstableProvider()或acquireProvider()获取IContentProvider,其是抽象方法

@Override
public final @Nullable Cursor query(final @RequiresPermission.Read @NonNull Uri uri,
                                    @Nullable String[] projection, @Nullable Bundle queryArgs,
                                    @Nullable CancellationSignal cancellationSignal) {
    ......
    IContentProvider unstableProvider = acquireUnstableProvider(uri);
    if (unstableProvider == null) {
        return null;
    }
    IContentProvider stableProvider = null;
    Cursor qCursor = null;
    try {
        ......            
        try {
            qCursor = unstableProvider.query(mPackageName, uri, projection,
                    queryArgs, remoteCancellationSignal);
        } catch (DeadObjectException e) {
            unstableProviderDied(unstableProvider);
            stableProvider = acquireProvider(uri);
            if (stableProvider == null) {
                return null;
            }
            qCursor = stableProvider.query(
                    mPackageName, uri, projection, queryArgs, remoteCancellationSignal);
        }
        if (qCursor == null) {
            return null;
        }
        qCursor.getCount();
        final IContentProvider provider = (stableProvider != null) ? stableProvider
                : acquireProvider(uri);
        final CursorWrapperInner wrapper = new CursorWrapperInner(qCursor, provider);
        stableProvider = null;
        qCursor = null;
        return wrapper;
    }.....
}

会调用ContextImpl.ApplicationContentResolver 的 acquireProvider()

private static final class ApplicationContentResolver extends ContentResolver {
    @UnsupportedAppUsage
    private final ActivityThread mMainThread;
    public ApplicationContentResolver(Context context, ActivityThread mainThread) {
        super(context);
        mMainThread = Objects.requireNonNull(mainThread);
    }
    @Override
    @UnsupportedAppUsage
    protected IContentProvider acquireProvider(Context context, String auth) {
        return mMainThread.acquireProvider(context,
                ContentProvider.getAuthorityWithoutUserId(auth),
                resolveUserIdFromAuthority(auth), true);
    }
	......
    @Override
    protected IContentProvider acquireUnstableProvider(Context c, String auth) {
        return mMainThread.acquireProvider(c,
                ContentProvider.getAuthorityWithoutUserId(auth),
                resolveUserIdFromAuthority(auth), false);
    }
    ......
}

调用到ActivityThread 的 acquireProvider()、acquireExistingProvider()判断IContentProvider是否已经加载到mProviderMap

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 {
        synchronized (getGetProviderLock(auth, userId)) {
            holder = ActivityManager.getService().getContentProvider(
                    getApplicationThread(), c.getOpPackageName(), auth, userId, stable);
        }
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
    if (holder == null) {
        ......
        return null;
    }
    ......
    holder = installProvider(c, holder, holder.info,
            true /*noisy*/, holder.noReleaseNeeded, stable);
    return holder.provider;
}

若没加载,则调用ActivityManagerService的getContentProvider(),startProcessLocked()启动ContentProvider所在的进程,进程入口方法为ActivityThread的main(),在此创建ActivityThread和主线程消息队列

public static void main(String[] args) {
    ......
    Looper.prepareMainLooper();
    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()));
            }
        }
    }
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    ......
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

上面调用

  • ActivityThread 的 attach()
  • ActivityManagerService 的 attachApplication()、attachApplicationLocked(),传入ApplicationThread,其是Binder,用于ActivityThread和ActivityManagerService之间的通信
  • ApplicationThread 的 bindApplication()、发送H.BIND_APPLICATION、handleBindApplication()

在handleBindApplication(),创建Application、加载ContentProviders、然后再调用Application的OnCreate()

private void handleBindApplication(AppBindData data) {
    ......
    Application app;
    try {
        app = data.info.makeApplication(data.restrictedBackupMode, null);
        .....
        if (!data.restrictedBackupMode) {
            if (!ArrayUtils.isEmpty(data.providers)) {
                installContentProviders(app, data.providers);
            }
        }
        try {
            mInstrumentation.onCreate(data.instrumentationArgs);
        }......
        try {
            mInstrumentation.callApplicationOnCreate(app);
        }......
    }......
}

在installContentProviders()中又调用installProvider()、instantiateProvider()通过反射创建ContentProvider,调用attachInfo()、回调onCreate()

private ContentProviderHolder installProvider(Context context,
                                              ContentProviderHolder holder, ProviderInfo info,
                                              boolean noisy, boolean noReleaseNeeded, boolean stable) {
    ......
    try {
        final java.lang.ClassLoader cl = c.getClassLoader();
        LoadedApk packageInfo = peekPackageInfo(ai.packageName, true);
        if (packageInfo == null) {
            packageInfo = getSystemContext().mPackageInfo;
        }
        localProvider = packageInfo.getAppFactory()
                .instantiateProvider(cl, info.name);
        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);
        localProvider.attachInfo(c, info);
    }.......
    synchronized (mProviderMap) {
        IBinder jBinder = provider.asBinder();
        if (localProvider != null) {
            ComponentName cname = new ComponentName(info.packageName, info.name);
            ProviderClientRecord pr = mLocalProvidersByName.get(cname);
            if (pr != null) {
                
                provider = pr.mProvider;
            } else {
                holder = new ContentProviderHolder(info);
                holder.provider = provider;
                holder.noReleaseNeeded = true;
                pr = installProviderAuthoritiesLocked(provider, localProvider, holder);
                mLocalProviders.put(jBinder, pr);
                mLocalProvidersByName.put(cname, pr);
            }
            retHolder = pr.mHolder;
        }
}

调用installProviderAuthoritiesLocked(),将ContentProvider封装到ProviderClientRecord存放在mProviderMap

private ProviderClientRecord installProviderAuthoritiesLocked(IContentProvider provider,
                                                              ContentProvider localProvider, ContentProviderHolder holder) {
    ......
    final ProviderClientRecord pcr = new ProviderClientRecord(
            auths, provider, localProvider, holder);
    for (String auth : auths) {
        final ProviderKey key = new ProviderKey(auth, userId);
        final ProviderClientRecord existing = mProviderMap.get(key);
        if (existing != null) {
            Slog.w(TAG, "Content provider " + pcr.mHolder.info.name
                    + " already published as " + auth);
        } else {
            mProviderMap.put(key, pcr);
        }
    }
    return pcr;
}
相关推荐
计算机徐师兄7 分钟前
Java基于SSM框架的无中介租房系统小程序【附源码、文档】
java·微信小程序·小程序·无中介租房系统小程序·java无中介租房系统小程序·无中介租房微信小程序
源码哥_博纳软云8 分钟前
JAVA智慧养老养老护理帮忙代办陪诊陪护小程序APP源码
java·开发语言·微信小程序·小程序·微信公众平台
zhangphil1 小时前
Android绘图Path基于LinearGradient线性动画渐变,Kotlin(2)
android·kotlin
忒可君1 小时前
C# winform 报错:类型“System.Int32”的对象无法转换为类型“System.Int16”。
java·开发语言
watl01 小时前
【Android】unzip aar删除冲突classes再zip
android·linux·运维
斌斌_____1 小时前
Spring Boot 配置文件的加载顺序
java·spring boot·后端
键盘上的蚂蚁-1 小时前
PHP爬虫类的并发与多线程处理技巧
android
路在脚下@2 小时前
Spring如何处理循环依赖
java·后端·spring
一个不秃头的 程序员2 小时前
代码加入SFTP JAVA ---(小白篇3)
java·python·github
丁总学Java2 小时前
--spring.profiles.active=prod
java·spring