第9章-四大组件的工作过程

四大组件的运行状态

Android中四大组件处了BroadcastReceiver之外,其他三种组件必须在清单文件中注册,BroadcastReceiver既可以在清单文件中注册,也可以在代码中注册。在调用方式上,Activity,Service,BroadcastReceiver需要借助Intent,ContentProvider无需借助Intent

Activity的工作过程

当调用startActivity方法时,Activity是如何被创建的?什么时候被创建的?需要分析

调用过程

调用过程非常复杂,而且不同版本的调用过程还不一样,只要知道最终Activity的创建和启动在ActivityThread中performLaunchActivity方法中

startActivity

代码跟踪

    @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        ...
        ...
        
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            // Note we want to go through this call for compatibility with
            // applications that may have overridden the method.
            startActivityForResult(intent, -1);
        }
    }

最终调用了startActivityForResult

startActivityForResult

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);

		//Activity在这里进行启动
            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);
        } else {
            if (options != null) {
                mParent.startActivityFromChild(this, intent, requestCode, options);
            } else {
                mParent.startActivityFromChild(this, intent, requestCode);
            }
        }
    }

执行startActivityForResult调用了mInstrumentation.execStartActivity方法

Instrumentation.execStartActivity

public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        ...
        ...
        try {
            intent.migrateExtraStreamToClipData(who);
            intent.prepareToLeaveProcess(who);
            //关键代码,新版本ActivityTaskManager.getService(),返回的是IActivityTaskManager,是IBinder接口,最终需要找的类是ActivityTaskManagerService
            //老版本最终看的是ActivityManagerService(AMS)
            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;
    }

新版本中的ActivityManagerService中的startActivity调用的是ActivityTaskManagerService中的方法

    public int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
            //从这里看出,调用的是ActivityTaskManagerService的startActivity
        return mActivityTaskManager.startActivity(caller, callingPackage, null, intent,
                resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions);
    }

ActivityTaskManagerService.startActivity

    @Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
            String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
            Bundle bOptions) {
        return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
                resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
                UserHandle.getCallingUserId());
    }

ActivityStarter.execute

try {
...
...
            int res;
            synchronized (mService.mGlobalLock) {
                final boolean globalConfigWillChange = mRequest.globalConfig != null
                        && mService.getGlobalConfiguration().diff(mRequest.globalConfig) != 0;
                final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
                if (stack != null) {
                    stack.mConfigWillChange = globalConfigWillChange;
                }
                if (DEBUG_CONFIGURATION) {
                    Slog.v(TAG_CONFIGURATION, "Starting activity when config will change = "
                            + globalConfigWillChange);
                }

                final long origId = Binder.clearCallingIdentity();

                res = resolveToHeavyWeightSwitcherIfNeeded();
                if (res != START_SUCCESS) {
                    return res;
                }
                res = executeRequest(mRequest);

                Binder.restoreCallingIdentity(origId);

                if (globalConfigWillChange) {
                    // If the caller also wants to switch to a new configuration, do so now.
                    // This allows a clean switch, as we are waiting for the current activity
                    // to pause (so we will not destroy it), and have not yet started the
                    // next activity.
                    mService.mAmInternal.enforceCallingPermission(
                            android.Manifest.permission.CHANGE_CONFIGURATION,
                            "updateConfiguration()");
                    if (stack != null) {
                        stack.mConfigWillChange = false;
                    }
                    if (DEBUG_CONFIGURATION) {
                        Slog.v(TAG_CONFIGURATION,
                                "Updating to new configuration after starting activity.");
                    }
                    mService.updateConfigurationLocked(mRequest.globalConfig, null, false);
                }

                // Notify ActivityMetricsLogger that the activity has launched.
                // ActivityMetricsLogger will then wait for the windows to be drawn and populate
                // WaitResult.
                mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(launchingState, res,
                        mLastStartActivityRecord);
                return getExternalResult(mRequest.waitResult == null ? res
                        : waitForResult(res, mLastStartActivityRecord));
            }
        } finally {
            onExecutionComplete();
        }

调用了executeRequest,在executeRequest中调用了ActivityStack中的startActivityLocked,调用了resumeTopActivityInnerLocked,接着调用ActivityStackSupervisor中的startSpecificActivity

ActivityStackSupervisor.startSpecificActivity

void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        final WindowProcessController wpc =
                mService.getProcessController(r.processName, r.info.applicationInfo.uid);

        boolean knownToBeDead = false;
        if (wpc != null && wpc.hasThread()) {
            try {
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }

            // If a dead object exception was thrown -- fall through to
            // restart the application.
            knownToBeDead = true;
        }

        r.notifyUnknownVisibilityLaunchedForKeyguardTransition();

        final boolean isTop = andResume && r.isTopRunningActivity();
        mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
    }

ActivityThread.performLaunchActivity

最终在这个方法创建和启动Activity,并返回

 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {}

performLaunchActivity

Activity创建和启动由这个方法完成,此方法定义在ActivityThread中

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
		//创建context,ContextImpl是Context的具体实现
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
    
    	//创建Activity
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
           
        //创建Application,这里返回Application,真正创建Application是在ActivityThread创建时创建的
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (activity != null) {

				//调用attach方法,关联context,创建PhoneWindow
                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);

				//设置activity主题
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    activity.setTheme(theme);
                }

				//调用onCreate方法
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }

            }
            //设置生命周期状态
            r.setState(ON_CREATE);

            synchronized (mResourcesManager) {
                mActivities.put(r.token, r);
            }

		//返回给了handleLaunchActivity
        return activity;
    }

Application的创建

在ActivityThread中main函数中,创建了ActivityThread,并且调用了attach方法

private void attach(boolean system, long startSeq){
	try {
                mInstrumentation = new Instrumentation();
                mInstrumentation.basicInit(this);
                ContextImpl context = ContextImpl.createAppContext(
                        this, getSystemContext().mPackageInfo);
				//这里创建了Application
                mInitialApplication = context.mPackageInfo.makeApplication(true, null);
                //调用Application的onCreate方法
                mInitialApplication.onCreate();
            } catch (Exception e) {
                throw new RuntimeException(
                        "Unable to instantiate Application():" + e.toString(), e);
            }
}

调用了LoadedApk中的makeApplication方法

public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {
            //如果Application已经创建,则返回
        if (mApplication != null) {
            return mApplication;
        }

        Application app = null;

        String appClass = mApplicationInfo.className;
        if (forceDefaultAppClass || (appClass == null)) {
            appClass = "android.app.Application";
        }

            final java.lang.ClassLoader cl = getClassLoader();

            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
			//调用Instrumentation.newApplication
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
            appContext.setOuterContext(app);
        return app;
    }

真正创建Application对象的是Instrumentation.newApplication,通过反射获取

    public Application newApplication(ClassLoader cl, String className, Context context)
            throws InstantiationException, IllegalAccessException, 
            ClassNotFoundException {
        Application app = getFactory(context.getPackageName())
                .instantiateApplication(cl, className);
        app.attach(context);
        return app;
    }


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

Activity的创建

在performLaunchActivity方法中调用了Instrumentation.newActivity创建,也是使用反射创建

    public Activity newActivity(ClassLoader cl, String className,
            Intent intent)
            throws InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        String pkg = intent != null && intent.getComponent() != null
                ? intent.getComponent().getPackageName() : null;
        return getFactory(pkg).instantiateActivity(cl, className, intent);
    }

    public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,
            @Nullable Intent intent)
            throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return (Activity) cl.loadClass(className).newInstance();
    }

Activity执行attach方法

关联context,创建phoneWindow

Activity执行onCreate方法

在performLaunchActivity中调用Instrumentation.callActivityOnCreate

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

调用Activity中的performCreate

@UnsupportedAppUsage
    final void performCreate(Bundle icicle, PersistableBundle persistentState) {

        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
       
    }

最终调用onCreate方法

Service的工作过程

Service分为两种工作状态,一种是启动状态(startService),用于执行后台计算,一种是绑定状态(bindService),主要用于其他组件和Service交互。这两种状态可以共存。

startService

调用了Activity的父类ContextWrapper中的startService方法,ContextWrapper继承Context

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

这个mBase变量是ContextImpl对象,这个是Context的子类,所以调用的是ContextImpl中的startService,

调用过程

ContextImpl.startService
    @Override
    public ComponentName startService(Intent service) {
        warnIfCallingFromSystemProcess();
        return startServiceCommon(service, false, mUser);
    }
ContextImpl.startServiceCommon
//调用AMS中的startService
 private ComponentName startServiceCommon(Intent service, boolean requireForeground,
            UserHandle user) {
            ComponentName cn = ActivityManager.getService().startService();
}
ActivityManagerService.startService
@Override
    public ComponentName startService()
            throws TransactionTooLargeException {
       
            try {
            	//关键方法,这个mServices类型是ActiveServices
                res = mServices.startServiceLocked(caller, service,
                        resolvedType, callingPid, callingUid,
                        requireForeground, callingPackage, callingFeatureId, userId);
            } finally {
                Binder.restoreCallingIdentity(origId);
            }
            return res;
        
    }
ActiveServices.startServiceLocked

这个方法调用了startServiceInnerLocked方法

ActiveServices.startServiceInnerLocked
ActiveServices.bringUpServiceLocked
ActiveServices.realStartServiceLocked

执行到这里,真正启动服务

private final void realStartServiceLocked(){
	//app.thread是ApplicationThread类型,是ActivityThread的内部类
	//
	app.thread.scheduleCreateService(r, r.serviceInfo,
                    mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
                    app.getReportedProcState());
}
ApplicationThread.scheduleCreateService

使用Handler H来中转,发送消息,执行ActivityThread.handleCreateService

public final void scheduleCreateService(IBinder token,
                ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
            updateProcessState(processState, false);
            CreateServiceData s = new CreateServiceData();
            s.token = token;
            s.info = info;
            s.compatInfo = compatInfo;

            sendMessage(H.CREATE_SERVICE, s);
        }
ActivityThread.handleCreateService

创建服务

handleCreateService

此方法在ActivityThread,创建服务的方法

private void handleCreateService(CreateServiceData data) {

            ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
            Application app = packageInfo.makeApplication(false, mInstrumentation);
            java.lang.ClassLoader cl = packageInfo.getClassLoader();

			//反射创建Service对象
            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());
			//执行onCreate方法
            service.onCreate();
            mServices.put(data.token, service);
           
    }

ActivityThread中的handleServiceArgs方法调用了Service中的onStartCommand方法

bindService

同样的,bindService也是ContextImpl中的方法。

调用过程

ContextImpl.bindService
    @Override
    public boolean bindService(
            Intent service, int flags, Executor executor, ServiceConnection conn) {
        warnIfCallingFromSystemProcess();
        return bindServiceCommon(service, conn, flags, null, null, executor, getUser());
    }
ContextImpl.bindServiceCommon
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
            String instanceName, Handler handler, Executor executor, UserHandle user) {
        // Keep this in sync with DevicePolicyManager.bindDeviceAdminServiceAsUser.
        IServiceConnection sd;

            if (executor != null) {
                sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags);
            } else {
                sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
            }
			//AMS执行绑定
            int res = ActivityManager.getService().bindIsolatedService(
                mMainThread.getApplicationThread(), getActivityToken(), service,
                service.resolveTypeIfNeeded(getContentResolver()),
                sd, flags, instanceName, getOpPackageName(), user.getIdentifier());

    }
ActivityManagerService.bindIsolatedService
 public int bindIsolatedService(){
synchronized(this) {
//ActiveServices
            return mServices.bindServiceLocked(caller, token, service,
                    resolvedType, connection, flags, instanceName, callingPackage, userId);
        }
}
ActiveServices.bindServiceLocked
ActiveServices.bringUpServiceLocked
ActiveServices.realStartServiceLocked

和startService一样,执行到这里就创建了Service,但是bind的方式还执行了requestServiceBindingLocked方法进行绑定

ActiveServices.requestServiceBindingLocked
private final boolean requestServiceBindingLocked(){
	//执行绑定
	r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
                        r.app.getReportedProcState());
}

同样的,也是执行了ApplicationThread的scheduleBindService方法,使用Handler H发送消息

        public final void scheduleBindService(IBinder token, Intent intent,
                boolean rebind, int processState) {
            updateProcessState(processState, false);
            BindServiceData s = new BindServiceData();
            s.token = token;
            s.intent = intent;
            s.rebind = rebind;

            if (DEBUG_SERVICE)
                Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
                        + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
            sendMessage(H.BIND_SERVICE, s);
        }
ActivityThread.handleBindService
private void handleBindService(BindServiceData data) {
        Service s = mServices.get(data.token);
					if (!data.rebind) {
                        IBinder binder = s.onBind(data.intent);
                        //调用AMS的publishService
                        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
mServices.publishServiceLocked((ServiceRecord)token, intent, service);
ActiveServices.publishServiceLocked
void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service){
	c.conn.connected(r.name, service, false);
}

connected方法是在LoadedApk.ServiceDispatcher.InnerConnection中执行
最终执行的代码

            // If there was an old service, it is now disconnected.
            if (old != null) {
                mConnection.onServiceDisconnected(name);
            }
            if (dead) {
                mConnection.onBindingDied(name);
            }
            // If there is a new viable service, it is now connected.
            if (service != null) {
                mConnection.onServiceConnected(name, service);
            } else {
                // The binding machinery worked, but the remote returned null from onBind().
                mConnection.onNullBinding(name);
            }

BroadcastReceiver的工作过程

ContentProvider的工作过程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值