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

这篇具有很好参考价值的文章主要介绍了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,调用execute(),调用resolveActivity()根据Intent匹配到对应的ActivityInfo

int execute() {
    try {
       	......
        if (mRequest.activityInfo == null) {
            mRequest.resolveActivity(mSupervisor);
        }

        int res;
        synchronized (mService.mGlobalLock) {
            ......
            res = executeRequest(mRequest);

            ......
            return getExternalResult(mRequest.waitResult == null ? res
                    : waitForResult(res, mLastStartActivityRecord));
        }
    }......
}
  • 调用 ActivityStarter 的 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();
        }
		......
        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);
......
if (r.isPersistable()) {
    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
    mInstrumentation.callActivityOnCreate(activity, r.state);
}

通过Instrumentation的callActivityOnCreate

public void callActivityOnCreate(Activity activity, Bundle icicle) {
    prePerformCreate(activity);
    activity.performCreate(icicle);
    postPerformCreate(activity);
}

调用activity的performCreate()、onCreate(),至此Activity启动完成

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    ......
    if (persistentState != null) {
        onCreate(icicle, persistentState);
    } else {
        onCreate(icicle);
    }
    ......
}

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()开始

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

上面调用到ContextImpl的registerReceiver()

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

@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,String broadcastPermission, Handler scheduler) {
    return registerReceiverInternal(receiver, getUserId(), filter, broadcastPermission, scheduler, getOuterContext(), 0);
}	

上面调用到ContextImpl的registerReceiverInternal()

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);
        }......
    }
    try {
        final Intent intent = ActivityManager.getService().registerReceiverWithFeature(
                mMainThread.getApplicationThread(), mBasePackageName, getAttributionTag(), rd, 
                filter, broadcastPermission, userId, flags);
        if (intent != null) {
            intent.setExtrasClassLoader(getClassLoader());
            intent.prepareToEnterProcess();
        }
        return intent;
    }......
}

上面调用的LoadedApkgetReceiverDispatcher()

  • 先根据context取出mReceivers
  • 判断BroadcastReceiver是否存在,存在取出对应的LoadedApk.ReceiverDispatcher
  • 否则根据BroadcastReceiver创建LoadedApk.ReceiverDispatcher存到map,再将map再存到mReceivers
public IIntentReceiver getReceiverDispatcher(BroadcastReceiver r,Context context, Handler handler, Instrumentation instrumentation, boolean registered) {
    synchronized (mReceivers) {
        LoadedApk.ReceiverDispatcher rd = null;
        ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> map = null;
        if (registered) {
            map = mReceivers.get(context);
            if (map != null) {
                rd = map.get(r);
            }
        }
        if (rd == null) {
            rd = new ReceiverDispatcher(r, context, handler,
                    instrumentation, registered);
            if (registered) {
                if (map == null) {
                    map = new ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>();
                    mReceivers.put(context, map);
                }
                map.put(r, rd);
            }
        } else {
            rd.validate(context, handler);
        }
        rd.mForgotten = false;
        return rd.getIIntentReceiver();
    }
}

上面调用ReceiverDispatcher的getIIntentReceiver(),返回LoadedApk.ReceiverDispatcher中的InnerReceiver(充当Binder),因为注册可能是跨进程的

static final class ReceiverDispatcher {

    final static class InnerReceiver extends IIntentReceiver.Stub {
        final WeakReference<LoadedApk.ReceiverDispatcher> mDispatcher;
        final LoadedApk.ReceiverDispatcher mStrongRef;

        InnerReceiver(LoadedApk.ReceiverDispatcher rd, boolean strong) {
            mDispatcher = new WeakReference<LoadedApk.ReceiverDispatcher>(rd);
            mStrongRef = strong ? rd : null;
        }
        ......
	}
      

    final IIntentReceiver.Stub mIIntentReceiver;
  
    final Context mContext;
    final Handler mActivityThread;
    final Instrumentation mInstrumentation;
    final boolean mRegistered;
	......
    ReceiverDispatcher(BroadcastReceiver receiver, Context context,
            Handler activityThread, Instrumentation instrumentation,
            boolean registered) {
        if (activityThread == null) {
            throw new NullPointerException("Handler must not be null");
        }

        mIIntentReceiver = new InnerReceiver(this, !registered);
        mReceiver = receiver;
        mContext = context;
        mActivityThread = activityThread;
        mInstrumentation = instrumentation;
        mRegistered = registered;
        ......
    }
}

随后调用到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()
  • 此外,在bindApplication()之后调用ActivityTaskManagerService中的LocalService的attachApplication(),调用RootWindowContainer的attachApplication()、startActivityForAttachedApplicationIfNeeded(),调用StackSupervisor的realStartActivityLocked()启动主Activity

在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文章来源地址https://www.toymoban.com/news/detail-681813.html

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;
}

到了这里,关于Android中级——四大组件工作过程的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • [Android 四大组件] --- Activity

    ​​Activity​​是一个Android的应用组件,它提供屏幕进行交互。每个Activity都会获得一个用于绘制其用户界面的窗口,窗口可以充满哦屏幕也可以小于屏幕并浮动在其他窗口之上。 一个应用通常是由多个彼此松散联系的Activity组成,一般会指定应用中的某个Activity为主活动,也

    2024年02月10日
    浏览(45)
  • Android四大组件之服务

    为什么要使用服务呢? 从上面的文字说,我们知道这个服务是用于执行长期后台运行的操作。有些时候,我们没有界面,但是程序仍然需要工作。比如说,我们播放音乐,在后台播放音乐。比如说,我们下载任务,在后台下载文件。这些都是没有界面 的后台运行程序,这些

    2024年02月14日
    浏览(81)
  • Android 四大组件启动

    service: startService启动过程分析 - Gityuan博客 | 袁辉辉的技术博客 在整个startService过程,从进程角度看服务启动过程 Process A进程: 是指调用startService命令所在的进程,也就是启动服务的发起端进程,比如点击桌面App图标,此处Process A便是Launcher所在进程。 system_server进程: 系统

    2024年04月11日
    浏览(40)
  • Android 四大组件之广播

    在Android应用开发中,广播组件是一项关键技术,被广泛用于各种任务和场景。无论是发送系统级广播,还是在应用内部实现组件间的通信,了解和掌握广播组件的工作原理和使用方法对于每个Android开发者来说都是至关重要的。本文旨在帮助你深入了解Android广播组件,并给出

    2024年02月06日
    浏览(47)
  • Android 四大组件之Activity详解

      最近在整理Android方面的知识,也算是对Android知识的一个复习总结。   Activity是Android组件中最基本也是最为常见用的四大组件之一,它提供一个可视化的用户界面,放置各种UI组件,与用户进行交互。一般来说,你所能看到界面都属于Activity。 右击包名——New——Acti

    2024年04月15日
    浏览(73)
  • Android复习(Android基础-四大组件)——Service与Activity通信

    我们前面学会了启动和停止服务的方法,但是服务虽然是在活动里启动的,但是启动服务之后,活动与服务之间基本没什么关系了。 正常情况,我们在Activity里调用startService()方法启动MyService这个服务,然后MyService的onCreate()和onStartCommand()方法就会得到执行。之后服务会一直处

    2024年02月13日
    浏览(44)
  • Android入门教程 | 四大组件之Service(前台服务,后台服务)

    Service是一种可在后台执行长时间运行操作而不提供界面的应用组件。服务可由其他应用组件启动,而且即使用户切换到其他应用,服务仍将在后台继续运行。 此外,组件可通过绑定到服务与之进行交互,甚至是执行进程间通信 (IPC)。 例如,服务可在后台处理网络事务、播放

    2024年02月05日
    浏览(56)
  • Android端MVVM从入门到实战(第一篇) - MVVM和四大官方组件

    MVVM是相对于MVC和MVP的一个概念,是一种架构模式。 1.1 MVC 传统的MVC中,View改变通知Controller进行处理,Controller处理结束后通知Model层更新,Model层更新以后通知View层渲染,指令单项流动,角色分工明确。但是MVC有三个缺点,1、三个角色互相持有对方依赖,因此很难复用其中任

    2024年02月04日
    浏览(44)
  • 【Android Studio】Android Studio修改代码编辑区(工作区)背景色

    Android Studio 字体大小及背景色的设置 1、 打开File—Settings 或者 Android Studio—Ctrl+Alt+s 2、 在setting对话框中选中“Editor-ColorsFonts-Font , 点击Save as,自定义一个主题,选择字体,size和行间距,保存。 3、设置背景色 选择-General-Text-Default Text,设置背景色。 青草绿:#e3edcd

    2024年04月27日
    浏览(46)
  • Android studio的安装的详细过程

    Android 开发环境 Eclipse Eclipse最初是由IBM公司开发的替代商业软件Visual Age for Java的下一代IDE开发环境,2001年11月贡献给开源社区,现在它由非营利软件供应商联盟Eclipse基金会(Eclipse Foundation)管理。 Eclipse是一种面向开发人员的编程环境,同时它也是 一个开放源代码的、基于

    2024年02月10日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包