四大组件的工作过程

本文详细探讨了Android系统的四大组件——Activity、Service、BroadcastReceiver和ContentProvider的运行状态及Activity的工作过程,包括启动Activity和其启动流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一、四大组件的运行状态


1、Activity(展示型组件)


Activity的主要作用是展示一个界面并和用户交互,它扮演的是一种前台界面的角色。
(1)需要在AndroidManifest中注册。
(2)需要借助Intent启动。有显示Intent和隐式Intent。隐式Intent指向一个或多个目标Activity组件,当然也可能没有任何一个Activity组件可以处理这个隐式Intent。
(3)对用户而言是可见的。
(4)可以具有特定的启动模式,比如singleTop、singleTask等。
(5)通过Activity的finish方法来结束一个Activity组件的运行。

2、Service(计算型组件)


Service用于在后台执行一系列计算任务。
(1)需要在AndroidManifest中注册。
(2)需要借助Intent启动。
(3)用户无法感知。
(4)两种状态:启动状态和绑定状态。
(5)启动状态:做后台计算,不需要和外界有直接的交互。尽管Service组件用于执行后台计算,但它本身是运行在主线程中的,因此耗时的后台计算仍然需要在单独的线程中去完成。
(6)绑定状态:这个时候Service内部同样可以进行后台计算,但是处于这种状态时外界可以很方便的和Service组件进行通信。IPC啊~
(7)灵活采用stopService和unBindService这两个方法才能完全停止一个Service组件。

3、BroadcastReceiver(消息型组件)


BroadcastReceiver用于在不同的组件乃至不同的应用之间传递消息。
(1)可以在AndroidManifest中静态注册,这种注册方式不需要应用启动就可以收到相应的广播;也可以在代码中动态注册,Context.registerReceiver()和 Context.unRegisterReceiver(),必须要启动应用才能注册并接收广播。
(2)需要借助Intent启动。
(3)用户无法感知。
(4)在实际开发中通过Context的一系列send方法来发送广播,被发送的广播会被系统发送给感兴趣的广播接收者,发送和接收过程的匹配是通过广播接收者的<intent-filter>来描述的。所以呢,BroadcastReceiver组件可以用来实现低耦合的观察者模式,观察者和被观察者之间可以没有任何耦合。
(5)不适合用来执行耗时操作。
(6)BroadcastReceiver组件一般来说不需要停止,它也没有停止的概念。

4、ContentProvider(数据共享型组件)


ContentProvider用于向其他组件乃至其他应用共享数据。
(1)需要在AndroidManifest中注册。
(2)无需借助Intent启动。
(3)用户无法感知。
(4)它的内部需要实现增删查改这四种操作,在它的内部维持着一份数据集合,这个数据集合既可以通过数据库来实现,也可以采用其他任何类型来实现,比如List和Map,ContentProvider对数据集合的具体实现并没有任何要求。
(5)注意点!!!ContentProvider内部的insert、deleted、update和query方法需要处理好线程同步,因为这几个方法是在Binder线程池中被调用的。
(6)ContentProvider无需手动停止。

二、Activity的工作过程


1、启动Activity

    Intent intent = new Intent(this, TestActivity.class);
    startActivity(intent);

2、Activity的启动过程


(1)startActivity:startActivity方法有好几种重载方式,但是它们最终都会调用startActivityForResult方法。
在Activity.java文件中:
    @Override
    public void startActivity(Intent intent, 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);
        }
    }
(2)startActivityForResult方法:在Activity.java文件中。
    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        /*
         * mParent代表的是ActivityGroup,
         * ActivityGroup最开始被用来在一个界面中嵌入多个Activity,
         * 但是其在API13中已经被废弃了,系统推荐采用Fragment来代替ActivityGroup。
         * */
    	if (mParent == null) {
    		/*
    		 * mMainThread.getApplicationThread()这个参数,它的类型是ApplicationThread,
    		 * ApplicationThread是ActivityThread的一个内部类,
    		 * 在后面的分析中可以发现,ApplicationThread和ActivityThread在Activity的启动过程中发挥着很重要的作用。
    		 * */
            Instrumentation.ActivityResult ar =
            		/*
            		 * 所以说Activity的启动过程转移到了Instrumentation中的execStartActivity方法:
            		 * */
                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) {
                // If this start is requesting a result, we can avoid making
                // the activity visible until the result is received.  Setting
                // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
                // activity hidden during this time, to avoid flickering.
                // This can only be done when a result is requested because
                // that guarantees we will get information back when the
                // activity is finished, no matter what happens to it.
                mStartedActivity = true;
            }

            final View decor = mWindow != null ? mWindow.peekDecorView() : null;
            if (decor != null) {
                decor.cancelPendingInputEvents();
            }
            // TODO Consider clearing/flushing other event sources and events for child windows.
        } else {
            if (options != null) {
                mParent.startActivityFromChild(this, intent, requestCode, options);
            } else {
                // Note we want to go through this method for compatibility with
                // existing applications that may have overridden it.
                mParent.startActivityFromChild(this, intent, requestCode);
            }
        }
    }
(3)Instrumentation的execStartActivity方法:在Instrumentation.java文件中。
    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
        if (mActivityMonitors != null) {
            synchronized (mSync) {
                final int N = mActivityMonitors.size();
                for (int i=0; i<N; i++) {
                    final ActivityMonitor am = mActivityMonitors.get(i);
                    if (am.match(who, null, intent)) {
                        am.mHits++;
                        if (am.isBlocking()) {
                            return requestCode >= 0 ? am.getResult() : null;
                        }
                        break;
                    }
                }
            }
        }
        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess();
            /*
             * 所以启动Activity的真正实现由ActivityManagerNative.getDefault().startActivity方法来完成。
             * 
             * ActivityManagerService继承自ActivityManagerNative,
             * 而ActivityManagerNative继承自Binder并实现了IActivityManager这个Binder接口,
             * 因此ActivityManagerService也是一个Binder,它是IActivityManager的具体实现。
             * 
             * 由于ActivityManagerNative.getDefault()其实是一个IActivityManager类型的Binder对象,
             * 因此它的具体实现是ActivityManagerService。
             * 所以说Activity的启动过程又转移到了ActivityManagerService中,
             * 然后再去看ActivityManagerService的startActivity方法。
             * */
            int result = ActivityManagerNative.getDefault()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, null, options);
            /*
             * 检查启动Activity的结果:
             * */
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
        }
        return null;
    }
在上面的代码中可以看到这一句:checkStartActivityResult(result, intent);我们去看看这个方法的源码:
    static void checkStartActivityResult(int res, Object intent) {
        if (res >= ActivityManager.START_SUCCESS) {
            return;
        }
        switch (res) {
            case ActivityManager.START_INTENT_NOT_RESOLVED:
            case ActivityManager.START_CLASS_NOT_FOUND:
                if (intent instanceof Intent && ((Intent)intent).getComponent() != null)
                	/*
                	 * 这个异常错误抛出最常见了。
                	 * 如果没有在AndroidManifest中注册Activity,就会抛出此异常。
                	 * */
                    throw new ActivityNotFoundException(
                            "Unable to find explicit activity class "
                            + ((Intent)intent).getComponent().toShortString()
                            + "; have you declared this activity in your AndroidManifest.xml?");
                throw new ActivityNotFoundException(
                        "No Activity found to handle " + intent);
            case ActivityManager.START_PERMISSION_DENIED:
                throw new SecurityException("Not allowed to start activity "
                        + intent);
            case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
                throw new AndroidRuntimeException(
                        "FORWARD_RESULT_FLAG used while also requesting a result");
            case ActivityManager.START_NOT_ACTIVITY:
                throw new IllegalArgumentException(
                        "PendingIntent is not an activity");
            default:
                throw new AndroidRuntimeException("Unknown error code "
                        + res + " when starting " + intent);
        }
    }
(3)在ActivityManagerNative.java文件中:
ActivityManagerNative.getDefault实际上就是ActivityManagerService,因此Activity的启动过程转移到了ActivityManagerService中。
    /*
     * 在Instrumentation的execStartActivity中用ActivityManagerNative的getDefault来获取一个IActivityManager的对象,
     * 而且这个IActivityManager的对象其实是一个Binder对象,它的具体实现是ActivityManagerService。
     * */
    static public IActivityManager getDefault() {
        return gDefault.get();
    }
    /*
     * 在ActivityManagernative中,ActivityManagerService这个Binder对象采用单例模式对外提供,
     * Singleton是一个单例的封装类,
     * 第一次调用它的get方法时它会通过create方法来初始化ActivityManagerService这个Binder对象,
     * 在后续的调用中则直接返回之前创建的对象。
     * */
    private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
        protected IActivityManager create() {
            IBinder b = ServiceManager.getService("activity");
            if (false) {
                Log.v("ActivityManager", "default service binder = " + b);
            }
            /*
             * 将Binder对象转换成对应IActivityManager的AIDL接口对象:
             * */
            IActivityManager am = asInterface(b);
            if (false) {
                Log.v("ActivityManager", "default service = " + am);
            }
            return am;
        }
    };
(4)ActivityManagerService的startActivity方法:
在ActivityManagerService.java文件中。
    @Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo,
            String resultWho, int requestCode, int startFlags,
            String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
    	/*
    	 * Activity的启动过程又转移到了startActivityAsUser方法中,再进去看看:
    	 * */
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode,
                startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
    }
(5)startActivityAsUser方法,在ActivityManagerService.java文件中。
    @Override
    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo,
            String resultWho, int requestCode, int startFlags,
            String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
        enforceNotIsolatedCaller("startActivity");
        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
                false, true, "startActivity", null);
        // TODO: Switch to user app stacks here.
        return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
                resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
                null, null, options, userId);
    }
(6)中间省略一大堆源码。上图:

(7)现在到了ActivityStackSupervisor的realStartActivityLocked方法中有如下一段代码:
			/*
			 * 这个app.thread的类型为IApplicationThread,
			 * IApplicationThread继承了IInterface接口,所以它是一个Binder类型的接口。
			 * 从IApplicationThread声明的接口方法可以看出,它的内部包含了大量启动、停止Activity的接口,
			 * 此外还包含了启动和停止服务的接口, 从接口方法的命名可以知道,
			 * IApplicationThread这个Binder接口的实现者完成了大量和Activity以及Service启动和停止相关的功能。
			 * 而IApplicationThread的实现者就是ActivityThread中的内部类ApplicationThread。
			 * 所以,绕来绕去,是用ApplicationThread中的scheduleLaunchActivity来启动Activity的。
			 */
			app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
					System.identityHashCode(r), r.info, new Configuration(
							mService.mConfiguration), r.compat,
					app.repProcState, r.icicle, results, newIntents,
					!andResume, mService.isNextTransitionForward(),
					profileFile, profileFd, profileAutoStop);
(8)app.thread的类型为IApplicationThread,IApplicationThread继承了IInterface接口,所以它是一个Binder类型的接口。从IApplicationThread声明的接口方法可以看出,它的内部包含了大量启动、停止Activity的接口,此外还包含了启动和停止服务的接口, 从接口方法的命名可以知道,IApplicationThread这个Binder接口的实现者完成了大量和Activity以及Service启动和停止相关的功能。而IApplicationThread的实现者就是ActivityThread中的内部类ApplicationThread。所以,绕来绕去,是用ApplicationThread中的scheduleLaunchActivity来启动Activity的。
public interface IApplicationThread extends IInterface {
    void schedulePauseActivity(IBinder token, boolean finished, boolean userLeaving,
            int configChanges, boolean dontReport) throws RemoteException;
    void scheduleStopActivity(IBinder token, boolean showWindow,
            int configChanges) throws RemoteException;
    void scheduleWindowVisibility(IBinder token, boolean showWindow) throws RemoteException;
    void scheduleSleeping(IBinder token, boolean sleeping) throws RemoteException;
    void scheduleResumeActivity(IBinder token, int procState, boolean isForward, Bundle resumeArgs)
            throws RemoteException;
    void scheduleSendResult(IBinder token, List<ResultInfo> results) throws RemoteException;
    void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
            ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
            String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state,
            PersistableBundle persistentState, List<ResultInfo> pendingResults,
            List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward,
            ProfilerInfo profilerInfo) throws RemoteException;
    void scheduleRelaunchActivity(IBinder token, List<ResultInfo> pendingResults,
            List<ReferrerIntent> pendingNewIntents, int configChanges,
            boolean notResumed, Configuration config) throws RemoteException;
    void scheduleNewIntent(List<ReferrerIntent> intent, IBinder token) throws RemoteException;
    void scheduleDestroyActivity(IBinder token, boolean finished,
            int configChanges) throws RemoteException;
    void scheduleReceiver(Intent intent, ActivityInfo info, CompatibilityInfo compatInfo,
            int resultCode, String data, Bundle extras, boolean sync,
            int sendingUser, int processState) throws RemoteException;
    static final int BACKUP_MODE_INCREMENTAL = 0;
    static final int BACKUP_MODE_FULL = 1;
    static final int BACKUP_MODE_RESTORE = 2;
    static final int BACKUP_MODE_RESTORE_FULL = 3;
    void scheduleCreateBackupAgent(ApplicationInfo app, CompatibilityInfo compatInfo,
            int backupMode) throws RemoteException;
    void scheduleDestroyBackupAgent(ApplicationInfo app, CompatibilityInfo compatInfo)
            throws RemoteException;
    void scheduleCreateService(IBinder token, ServiceInfo info,
            CompatibilityInfo compatInfo, int processState) throws RemoteException;
    void scheduleBindService(IBinder token,
            Intent intent, boolean rebind, int processState) throws RemoteException;
    void scheduleUnbindService(IBinder token,
            Intent intent) throws RemoteException;
    void scheduleServiceArgs(IBinder token, boolean taskRemoved, int startId,
            int flags, Intent args) throws RemoteException;
    void scheduleStopService(IBinder token) throws RemoteException;
    static final int DEBUG_OFF = 0;
    static final int DEBUG_ON = 1;
    static final int DEBUG_WAIT = 2;
    void bindApplication(String packageName, ApplicationInfo info, List<ProviderInfo> providers,
            ComponentName testName, ProfilerInfo profilerInfo, Bundle testArguments,
            IInstrumentationWatcher testWatcher, IUiAutomationConnection uiAutomationConnection,
            int debugMode, boolean openGlTrace, boolean restrictedBackupMode, boolean persistent,
            Configuration config, CompatibilityInfo compatInfo, Map<String, IBinder> services,
            Bundle coreSettings) throws RemoteException;
    void scheduleExit() throws RemoteException;
    void scheduleSuicide() throws RemoteException;
    void scheduleConfigurationChanged(Configuration config) throws RemoteException;
    void updateTimeZone() throws RemoteException;
    void clearDnsCache() throws RemoteException;
    void setHttpProxy(String proxy, String port, String exclList,
            Uri pacFileUrl) throws RemoteException;
    void processInBackground() throws RemoteException;
    void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args)
            throws RemoteException;
    void dumpProvider(FileDescriptor fd, IBinder servicetoken, String[] args)
            throws RemoteException;
    void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
            int resultCode, String data, Bundle extras, boolean ordered,
            boolean sticky, int sendingUser, int processState) throws RemoteException;
    void scheduleLowMemory() throws RemoteException;
    void scheduleActivityConfigurationChanged(IBinder token) throws RemoteException;
    void profilerControl(boolean start, ProfilerInfo profilerInfo, int profileType)
            throws RemoteException;
    void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd)
            throws RemoteException;
    void setSchedulingGroup(int group) throws RemoteException;
    static final int PACKAGE_REMOVED = 0;
    static final int EXTERNAL_STORAGE_UNAVAILABLE = 1;
    void dispatchPackageBroadcast(int cmd, String[] packages) throws RemoteException;
    void scheduleCrash(String msg) throws RemoteException;
    void dumpActivity(FileDescriptor fd, IBinder servicetoken, String prefix, String[] args)
            throws RemoteException;
    void setCoreSettings(Bundle coreSettings) throws RemoteException;
    void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) throws RemoteException;
    void scheduleTrimMemory(int level) throws RemoteException;
    void dumpMemInfo(FileDescriptor fd, Debug.MemoryInfo mem, boolean checkin, boolean dumpInfo,
            boolean dumpDalvik, String[] args) throws RemoteException;
    void dumpGfxInfo(FileDescriptor fd, String[] args) throws RemoteException;
    void dumpDbInfo(FileDescriptor fd, String[] args) throws RemoteException;
    void unstableProviderDied(IBinder provider) throws RemoteException;
    void requestAssistContextExtras(IBinder activityToken, IBinder requestToken, int requestType)
            throws RemoteException;
    void scheduleTranslucentConversionComplete(IBinder token, boolean timeout)
            throws RemoteException;
    void scheduleOnNewActivityOptions(IBinder token, ActivityOptions options)
            throws RemoteException;
    void setProcessState(int state) throws RemoteException;
    void scheduleInstallProvider(ProviderInfo provider) throws RemoteException;
    void updateTimePrefs(boolean is24Hour) throws RemoteException;
    void scheduleCancelVisibleBehind(IBinder token) throws RemoteException;
    void scheduleBackgroundVisibleBehindChanged(IBinder token, boolean enabled) throws RemoteException;
    void scheduleEnterAnimationComplete(IBinder token) throws RemoteException;

    String descriptor = "android.app.IApplicationThread";

    ...
}
(9)ApplicationThread继承了ApplicationThreadNative,而ApplicationThreadNative则继承了Binder并实现了IApplicationThread接口。其实ApplicationThreadNative的作用其实和系统为AIDL文件生成的类是一样的。
    private class ApplicationThread extends ApplicationThreadNative
    public abstract  class ApplicationThreadNative extends Binder implements IApplicationThread
ApplicationThreadNative的内部还有一个ApplicationThreadProxy类,这个类的实现如下所示:其实这个内部类也是系统为AIDL文件自动生成的代理类:
    class ApplicationThreadProxy implements IApplicationThread {
        private final IBinder mRemote;
        
        public ApplicationThreadProxy(IBinder remote) {
            mRemote = remote;
        }
        
        public final IBinder asBinder() {
            return mRemote;
        }
        
        public final void schedulePauseActivity(IBinder token, boolean finished,
                boolean userLeaving, int configChanges, boolean dontReport) throws RemoteException {
            Parcel data = Parcel.obtain();
            data.writeInterfaceToken(IApplicationThread.descriptor);
            data.writeStrongBinder(token);
            data.writeInt(finished ? 1 : 0);
            data.writeInt(userLeaving ? 1 :0);
            data.writeInt(configChanges);
            data.writeInt(dontReport ? 1 : 0);
            mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, null,
                    IBinder.FLAG_ONEWAY);
            data.recycle();
        }


        public final void scheduleStopActivity(IBinder token, boolean showWindow,
                int configChanges) throws RemoteException {
            Parcel data = Parcel.obtain();
            data.writeInterfaceToken(IApplicationThread.descriptor);
            data.writeStrongBinder(token);
            data.writeInt(showWindow ? 1 : 0);
            data.writeInt(configChanges);
            mRemote.transact(SCHEDULE_STOP_ACTIVITY_TRANSACTION, data, null,
                    IBinder.FLAG_ONEWAY);
            data.recycle();
        }
        
        ...
        
    }
所以呢,这个ApplicationThreadNative就是IApplicationThread的实现者。由于ApplicationThreadNative被系统定义为抽象类,所以ApplicationThread就成了IApplicationThread最终的实现者。所以啊,绕了一大圈,Activity的启动过程最终回到了ApplicationThread中,ApplicationThread通过scheduleLaunchActivity方法来启动Activity:
这个方法是ActivityThread.java文件中的ApplicationThread内部类的scheduleLaunchActivity方法:scheduleLaunchActivity的实现很简单,就是发送一个启动Activity的消息交由Handler处理。这个Handler的名字很简洁,H。
        public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
                int procState, Bundle state, List<ResultInfo> pendingResults,
                List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
                String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {

            updateProcessState(procState, false);

            ActivityClientRecord r = new ActivityClientRecord();

            r.token = token;
            r.ident = ident;
            r.intent = intent;
            r.activityInfo = info;
            r.compatInfo = compatInfo;
            r.state = state;

            r.pendingResults = pendingResults;
            r.pendingIntents = pendingNewIntents;

            r.startsNotResumed = notResumed;
            r.isForward = isForward;

            r.profileFile = profileName;
            r.profileFd = profileFd;
            r.autoStopProfiler = autoStopProfiler;

            updatePendingConfiguration(curConfig);

            queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
        }
    private void queueOrSendMessage(int what, Object obj) {
        queueOrSendMessage(what, obj, 0, 0);
    }
    private void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
        synchronized (this) {
            if (DEBUG_MESSAGES) Slog.v(
                TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
                + ": " + arg1 + " / " + obj);
            Message msg = Message.obtain();
            msg.what = what;
            msg.obj = obj;
            msg.arg1 = arg1;
            msg.arg2 = arg2;
            mH.sendMessage(msg);
        }
    }
(10)接下来看一下Handler H对消息的处理:
        public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
            /*
             * 启动Activity:
             * */
                case LAUNCH_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                    ActivityClientRecord r = (ActivityClientRecord)msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    /*
                     * 又转到这里了:
                     * */
                    handleLaunchActivity(r, null);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;
                ...
        } 
(11)handleLaunchActivity方法:
    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();


        if (r.profileFd != null) {
            mProfiler.setProfiler(r.profileFile, r.profileFd);
            mProfiler.startProfiling();
            mProfiler.autoStopProfiler = r.autoStopProfiler;
        }


        // Make sure we are running with the most recent config.
        handleConfigurationChanged(null, null);


        if (localLOGV) Slog.v(
            TAG, "Handling launch of " + r);
        /*
         * 启动Activity终极大Boss在此!!!!
         * */
        Activity a = performLaunchActivity(r, customIntent);


        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            Bundle oldState = r.state;
            /*
             * 调用Activity的onResume方法:
             * */
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed);


            if (!r.activity.mFinished && r.startsNotResumed) {
                // The activity manager actually wants this one to start out
                // paused, because it needs to be visible but isn't in the
                // foreground.  We accomplish this by going through the
                // normal startup (because activities expect to go through
                // onResume() the first time they run, before their window
                // is displayed), and then pausing it.  However, in this case
                // we do -not- need to do the full pause cycle (of freezing
                // and such) because the activity manager assumes it can just
                // retain the current state it has.
                try {
                    r.activity.mCalled = false;
                    mInstrumentation.callActivityOnPause(r.activity);
                    // We need to keep around the original state, in case
                    // we need to be created again.  But we only do this
                    // for pre-Honeycomb apps, which always save their state
                    // when pausing, so we can not have them save their state
                    // when restarting from a paused state.  For HC and later,
                    // we want to (and can) let the state be saved as the normal
                    // part of stopping the activity.
                    if (r.isPreHoneycomb()) {
                        r.state = oldState;
                    }
                    if (!r.activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onPause()");
                    }


                } catch (SuperNotCalledException e) {
                    throw e;


                } catch (Exception e) {
                    if (!mInstrumentation.onException(r.activity, e)) {
                        throw new RuntimeException(
                                "Unable to pause activity "
                                + r.intent.getComponent().toShortString()
                                + ": " + e.toString(), e);
                    }
                }
                r.paused = true;
            }
        } else {
            // If there was an error, for any reason, tell the activity
            // manager to stop us.
            try {
                ActivityManagerNative.getDefault()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null);
            } catch (RemoteException ex) {
                // Ignore
            }
        }
    }
其中handleResumeActivity方法调用Activity的onResume方法!!!
(12)performLaunchActivity这个方法主要完成了如下几件事:
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");

    	/*
    	 * 第一步:从ActivityClientRecord中获取待启动的Activity的组件信息:
    	 * */
        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);
        }

        /*
         * 第二步:通过Instrumentation的newActivity方法使用类加载器创建Activity对象。
         * */
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
            /*
             * 通过类加载器创建Activity的实例对象:
             * */
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            if (r.state != null) {
                r.state.setClassLoader(cl);
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to instantiate activity " + component
                    + ": " + e.toString(), e);
            }
        }

        /*
         * 第三步:通过LoadedApk的makeApplication方法来尝试创建Application对象,
         * 而且一个应用只能有一个Application对象。
         * Application对象的创建也是通过Instrumentation来完成的,这个过程和Activity对象的创建一样,
         * 都是通过类加载器来实现的。
         * Application创建完毕后,系统会通过Instrumentation的callApplicationOnCreate来调用Application的onCreate方法。
         * */
        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
            if (localLOGV) Slog.v(
                    TAG, r + ": app=" + app
                    + ", appName=" + app.getPackageName()
                    + ", pkg=" + r.packageInfo.getPackageName()
                    + ", comp=" + r.intent.getComponent().toShortString()
                    + ", dir=" + r.packageInfo.getAppDir());

            if (activity != null) {
            	/*
            	 * 第四步:创建ContextImpl对象并通过Activity的attach方法来完成一些重要数据的初始化。
            	 * 这里有一堆Activity运行过程中所依赖的上下文环境变量,
            	 * 并通过Activity的attach方法来将这些环境变量与Activity相关联:
            	 * (2)ContextImpl是一个很重要的数据结构,它是Context的具体实现,
            	 * Context中改的大部分逻辑都是由ContextImpl来完成的。
            	 * ContextImpl是通过Activity的attach方法来和Activity建立关联的。
            	 * (3)此外,在attach方法中Activity还会完成Window的创建并建立自己和Window的关联,
            	 * 这样当Window接收到外部输入事件后就可以将事件传递给Activity。
            	 * */
                Context appContext = createBaseContextForActivity(r, activity);
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                        + r.activityInfo.name + " with config " + config);
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config);

                if (customIntent != null) {
                    activity.mIntent = customIntent;
                }
                r.lastNonConfigurationInstances = null;
                activity.mStartedActivity = false;
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    activity.setTheme(theme);
                }

                activity.mCalled = false;
                /*
                 * 第五步:调用Activity的onCreate方法:
                 * 到此为止,Activity也就完成了整个启动过程,
                 * 呵呵哒。
                 * */
                mInstrumentation.callActivityOnCreate(activity, r.state);
                if (!activity.mCalled) {
                    throw new SuperNotCalledException(
                        "Activity " + r.intent.getComponent().toShortString() +
                        " did not call through to super.onCreate()");
                }
                r.activity = activity;
                r.stopped = true;
                if (!r.activity.mFinished) {
                    activity.performStart();
                    r.stopped = false;
                }
                if (!r.activity.mFinished) {
                    if (r.state != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                    }
                }
                if (!r.activity.mFinished) {
                    activity.mCalled = false;
                    mInstrumentation.callActivityOnPostCreate(activity, r.state);
                    if (!activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onPostCreate()");
                    }
                }
            }
            r.paused = true;

            mActivities.put(r.token, r);

        } catch (SuperNotCalledException e) {
            throw e;

        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to start activity " + component
                    + ": " + e.toString(), e);
            }
        }

        return activity;
    }







启动Activity的整体流程:

startActivity —— (startActivity中调用)startActivityForResult —— (startActivityForResult中调用)Instrumentation.execStartActivity ——(execStartActivity中调用)ActivityManagerNative.getDefault().startActivity也就相当于ActivityManagerService的startActivity(IPC)——(startActivity中调用)startActivityAsUser ——(startActivityAsUser中调用)ActivityStackSupervisor.startActivityMayWait —— (startActivityMayWait中调用)startActivityLocked —— (startActivityLocked 中调用)startActivityUncheckedLocked —— (startActivityUncheckedLocked 中调用)ActivityStack的resumeTopActivityLocked(此时已经从ActivityStackSupervisor转移到了ActivityStack) —— (resumeTopActivityLocked中调用resumeTopActivityInnerLocked —— (resumeTopActivityInnerLocked中调用ActivityStackSupervisor的startSpecificActivityLocked(此时又从ActivityStack转移到了ActivityStackSupervisor) —— (startSpecificActivityLocked中调用)realStartActivityLocked —— (realStartActivityLocked中调用)app.thread.scheduleLaunchActivity(app.thread也就是IApplicationThread)(也就是ApplicationThread的scheduleLaunchActivity)——  (scheduleLaunchActivity中调用)queueOrSendMessage —— Handler H的handleLaunchActivity —— (handleLaunchActivity 中调用)performLaunchActivity ——(execStartActivity中调用)checkStartActivityResult

声明:ActivityManagerService是Binder,ApplicationThread是Binder。





















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值