原创

Activity的工作工程

基于android8.0 源码解析

Activity是android的四大组件之一,主要用于向用户展示一个界面,并可以接收用户的输入信息进行交互。因为系统对其做了很好的封装,所以我们在使用的时候简单了很多。导致我们很少注意他的内部实现流程,今天通过阅读源码的方式来认识一下activity的启动过程。

进入一个activity无非就是

1.从手机桌面进入app

2.从app内部的一个页面进入另外一个页面

3.当然也有从A APP 进入B APP页面

其实1 就是系统应用launcher的界面进入一个app的过程和3是一样的。

不管从哪里过来,进入一个新的Activity都会调用 “ starActivityForResult ”这个方法。通过进入“starActivity”方法可以看到有几个重载的“starActivity”方法都调用了“ starActivityForResult ”方法,咱们来近一步的看一下这个方法是如何实现的。

@Override
public void startActivityForResult(
String who, Intent intent, int requestCode, @Nullable Bundle options) {
Uri referrer = onProvideReferrer();
if (referrer != null) {
intent.putExtra(Intent.EXTRA_REFERRER, referrer);
}
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, who,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, who, requestCode,
ar.getResultCode(), ar.getResultData());
}
cancelInputsAndStartExitTransition(options);
}
其中3个参数: 1.intent:包含启动activity的信息。
2.requestCode:请求标识字段(略过)
3.options:存储一些启动activity的参数,比如切换动画,一些附带数据等等,详细的可以看ActivityOptions类。常用的我们默认为null。
if (mParent == null) {中的mParent 代表的是ActivityGroup,ActivityGroup最开始被用来在一个界面嵌入多个字Activity,但是在API13以后被废弃了,起而代之的是Fragment。
在mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken, this,intent, requestCode, options);这个方法中需要注意一下mMainThread.getApplicationThread()这个参数他的类型是ApplicationThread,根据调用来看ApplicationThread是来自于ActivityThread的内部类。接着我们根据Instrumentation.ActivityResult进入Instrumentation这个类中。查看调用的execStartActivity方法。

public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
Uri referrer = target != null ? target.onProvideReferrer() : null;
if (referrer != null) {
intent.putExtra(Intent.EXTRA_REFERRER, referrer);
}
if (mActivityMonitors != null) {
synchronized (mSync) {
final int N = mActivityMonitors.size();
for (int i=0; i= 0 ? am.getResult() : null;
}
break;
}
}
}
}
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), 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;
}
从上面的方法可以看到Activity的启动是由 ActivityManager.getService() 的starActivity完成的,那么ActivityManager.getService返回的是什么呢?

public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
查看 IActivityManagerSingleton

private static final Singleton IActivityManagerSingleton =
new Singleton() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};

通过final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);获取一个关联了系统服务ActivityManagerService的Binder对象
通过final IActivityManager am = IActivityManager.Stub.asInterface(b);返回一个IActivityManager的代理对象,基于Binder机制,通过调用代理对象的方法,使得系统服务ActivityManagerService对应的方法被调用

回到ActivityManager.getService() .startActivity() 就是IActivityManager的代理对象调用了starActivity对象。通过Binder机制,他会使ActivityManagerService的startActivity方法被调用,因此activity的启动就交给了系统。

在execStartActivity方法中还有一个方法值得留意一下那就是checkStartActivityResult(result, intent); 看起来是像在检查activity的启动过程一样。我们来具体看他的实现。

/* @hide /
public static void checkStartActivityResult(int res, Object intent) {
if (!ActivityManager.isStartResultFatalError(res)) {
return;
}
switch (res) {
case ActivityManager.START_INTENT_NOT_RESOLVED:
case ActivityManager.START_CLASS_NOT_FOUND:
if (intent instanceof Intent && ((Intent)intent).getComponent() != null)
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);
    

从上面的代码可以看出就是在检查Activity的启动结果,当无法正确启动的时候会抛出异常,其中最熟悉的就是"Unable to find explicit activity class "+ ((Intent)intent).getComponent().toShortString() + "; have you declared this activity in your AndroidManifest.xml©");了吧。这个是没有在清淡文件中注册的时候报的异常。

我们接着分析ActivityManagerService是如何启动一个activity的。ActivityManagerService以下简称AMS。

首先我们看AMS的starActivity方法。
咱们先要找到ActivityManagerService这个类,路径SDK-source-android26-com-android-service-am-ActivityManagerService具体如下面截图。

进入AMS类找到startActivity方法

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

而startActivity方法调用了startActivityAsUser方法

@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
enforceNotIsolatedCaller("startActivity");
userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
userId, false, ALLOW_FULL_ONLY, "startActivity", null);
// TODO: Switch to user app stacks here.
return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, bOptions, false, userId, null, null,
"startActivityAsUser");
}
从中有可以看到AMS的activity启动又转移到了mActivityStarter 也就是ActivityStarter类的startActivityMayWait方法中

查看ActivityStarter源码如下:
final int startActivityMayWait(IApplicationThread caller, int callingUid,
String callingPackage, Intent intent, String resolvedType,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, WaitResult outResult,
Configuration globalConfig, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
IActivityContainer iContainer, TaskRecord inTask, String reason) {

    //...code

    int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voiceSession, voiceInteractor,
                resultTo, resultWho, requestCode, callingPid,
                callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, outRecord, container,
                inTask, reason);

    //...code        

}

int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
TaskRecord inTask, String reason) {

//...code    

    mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
            aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
            callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
            options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
            container, inTask);
//...code    

}

//继续查看

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
TaskRecord inTask) {

//...code

doPendingActivityLaunchesLocked(false);

//...code

}

final void doPendingActivityLaunchesLocked(boolean doResume) {
//...code

            startActivity(pal.r, pal.sourceRecord, null, null, pal.startFlags, resume, null,
                    null, null /*outRecords*/);

//...code

}

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
//...code

        result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, doResume, options, inTask, outActivity);

   //...code 

}

// Note: This method should only be called from {@link startActivity}.
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
//...code

mSupervisor.resumeFocusedStackTopActivityLocked();

//...code 

}

变量mSupervisor是一个ActivityStackSupervisor对象。
查看ActivityStackSupervisor源码如下:
boolean resumeFocusedStackTopActivityLocked() {
return resumeFocusedStackTopActivityLocked(null, null, null);
}

//继续查看

boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
//...code

mFocusedStack.resumeTopActivityUncheckedLocked(null, null);

//...code

}

mFocusedStack是一个ActivityStack对象;
ActivityStack源码如下:
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mStackSupervisor.inResumeTopActivity) {
//...code

result = resumeTopActivityInnerLocked(prev, options);

//...code

}

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
//...code

mStackSupervisor.startSpecificActivityLocked(next, true, true);

//...code

}

mSupervisor是一个ActivityStackSupervisor对象;

   查看ActivityStackSupervisor源码如下:

void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {

//...code

realStartActivityLocked(r, app, andResume, checkConfig);

//...code

}

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
//...code

app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                System.identityHashCode(r), r.info,
                // TODO: Have this take the merged configuration instead of separate global and
                // override configs.
                mergedConfiguration.getGlobalConfiguration(),
                mergedConfiguration.getOverrideConfiguration(), r.compat,
                r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                r.persistentState, results, newIntents, !andResume,
                mService.isNextTransitionForward(), profilerInfo);

//...code        

}
为了更清晰的看到AMS、ActivityStarter、ActivityStackSupervisor、ActivityStack 方法调用的关系画了下面的图

变量app是一个ProcessRecord对象,它的成员变量threadIApplicationThread类型,因此app.thread是一个IApplicationThread的代理对象

那我们继续查看IApplicationThread

public interface IApplicationThread extends IInterface {
int BACKUP_MODE_INCREMENTAL = 0;
int BACKUP_MODE_FULL = 1;
int BACKUP_MODE_RESTORE = 2;
int DEBUG_OFF = 0;
int DEBUG_ON = 1;
int DEBUG_WAIT = 2;
int PACKAGE_REMOVED = 0;
int EXTERNAL_STORAGE_UNAVAILABLE = 1;
String descriptor = "android.app.IApplicationThread";
int SCHEDULE_PAUSE_ACTIVITY_TRANSACTION = 1;
int SCHEDULE_STOP_ACTIVITY_TRANSACTION = 3;
int SCHEDULE_WINDOW_VISIBILITY_TRANSACTION = 4;
int SCHEDULE_RESUME_ACTIVITY_TRANSACTION = 5;
int SCHEDULE_SEND_RESULT_TRANSACTION = 6;
int SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION = 7;
int SCHEDULE_NEW_INTENT_TRANSACTION = 8;
int SCHEDULE_FINISH_ACTIVITY_TRANSACTION = 9;
int SCHEDULE_RECEIVER_TRANSACTION = 10;
int SCHEDULE_CREATE_SERVICE_TRANSACTION = 11;
int SCHEDULE_STOP_SERVICE_TRANSACTION = 12;
int BIND_APPLICATION_TRANSACTION = 13;
int SCHEDULE_EXIT_TRANSACTION = 14;
int REQUEST_THUMBNAIL_TRANSACTION = 15;
int SCHEDULE_CONFIGURATION_CHANGED_TRANSACTION = 16;
int SCHEDULE_SERVICE_ARGS_TRANSACTION = 17;
int UPDATE_TIME_ZONE_TRANSACTION = 18;
int PROCESS_IN_BACKGROUND_TRANSACTION = 19;
int SCHEDULE_BIND_SERVICE_TRANSACTION = 20;
int SCHEDULE_UNBIND_SERVICE_TRANSACTION = 21;
int DUMP_SERVICE_TRANSACTION = 22;
int SCHEDULE_REGISTERED_RECEIVER_TRANSACTION = 23;
int SCHEDULE_LOW_MEMORY_TRANSACTION = 24;
int SCHEDULE_ACTIVITY_CONFIGURATION_CHANGED_TRANSACTION = 25;
int SCHEDULE_RELAUNCH_ACTIVITY_TRANSACTION = 26;
int PROFILER_CONTROL_TRANSACTION = 28;
int SET_SCHEDULING_GROUP_TRANSACTION = 29;
int SCHEDULE_CREATE_BACKUP_AGENT_TRANSACTION = 30;
int SCHEDULE_DESTROY_BACKUP_AGENT_TRANSACTION = 31;
int GET_MEMORY_INFO_TRANSACTION = 32;
int SCHEDULE_SUICIDE_TRANSACTION = 33;
int DISPATCH_PACKAGE_BROADCAST_TRANSACTION = 34;
int SCHEDULE_CRASH_TRANSACTION = 35;

void schedulePauseActivity(IBinder var1, boolean var2, boolean var3, int var4) throws RemoteException;

void scheduleStopActivity(IBinder var1, boolean var2, int var3) throws RemoteException;

void scheduleWindowVisibility(IBinder var1, boolean var2) throws RemoteException;

void scheduleResumeActivity(IBinder var1, boolean var2) throws RemoteException;

void scheduleSendResult(IBinder var1, List<ResultInfo> var2) throws RemoteException;

void scheduleLaunchActivity(Intent var1, IBinder var2, int var3, ActivityInfo var4, Bundle var5, List<ResultInfo> var6, List<Intent> var7, boolean var8, boolean var9) throws RemoteException;

void scheduleRelaunchActivity(IBinder var1, List<ResultInfo> var2, List<Intent> var3, int var4, boolean var5, Configuration var6) throws RemoteException;

void scheduleNewIntent(List<Intent> var1, IBinder var2) throws RemoteException;

void scheduleDestroyActivity(IBinder var1, boolean var2, int var3) throws RemoteException;

void scheduleReceiver(Intent var1, ActivityInfo var2, int var3, String var4, Bundle var5, boolean var6) throws RemoteException;

void scheduleCreateBackupAgent(ApplicationInfo var1, int var2) throws RemoteException;

void scheduleDestroyBackupAgent(ApplicationInfo var1) throws RemoteException;

void scheduleCreateService(IBinder var1, ServiceInfo var2) throws RemoteException;

void scheduleBindService(IBinder var1, Intent var2, boolean var3) throws RemoteException;

void scheduleUnbindService(IBinder var1, Intent var2) throws RemoteException;

void scheduleServiceArgs(IBinder var1, int var2, int var3, Intent var4) throws RemoteException;

void scheduleStopService(IBinder var1) throws RemoteException;

void bindApplication(String var1, ApplicationInfo var2, List<ProviderInfo> var3, ComponentName var4, String var5, Bundle var6, IInstrumentationWatcher var7, int var8, boolean var9, Configuration var10, Map<String, IBinder> var11) throws RemoteException;

void scheduleExit() throws RemoteException;

void scheduleSuicide() throws RemoteException;

void requestThumbnail(IBinder var1) throws RemoteException;

void scheduleConfigurationChanged(Configuration var1) throws RemoteException;

void updateTimeZone() throws RemoteException;

void processInBackground() throws RemoteException;

void dumpService(FileDescriptor var1, IBinder var2, String[] var3) throws RemoteException;

void scheduleRegisteredReceiver(IIntentReceiver var1, Intent var2, int var3, String var4, Bundle var5, boolean var6, boolean var7) throws RemoteException;

void scheduleLowMemory() throws RemoteException;

void scheduleActivityConfigurationChanged(IBinder var1) throws RemoteException;

void profilerControl(boolean var1, String var2, ParcelFileDescriptor var3) throws RemoteException;

void setSchedulingGroup(int var1) throws RemoteException;

void getMemoryInfo(MemoryInfo var1) throws RemoteException;

void dispatchPackageBroadcast(int var1, String[] var2) throws RemoteException;

void scheduleCrash(String var1) throws RemoteException;

}
IApplicationThread 继承了IInterface接口,那接着咱们继续看看IInterface接口

public interface IInterface
{
/**

 * Retrieve the Binder object associated with this interface.
 * You must use this instead of a plain cast, so that proxy objects
 * can return the correct result.
 */
public IBinder asBinder();

}
从IInterface接口中可以看出他是一个Binder类型的接口。我们返回IApplicationThread类继续查看发现了大量启动、停止Activity的接口,此外还包含了启动停止服务的接口。从方法名上来看IApplicationThread类这个Binder接口的实现完成了大量的Activity和Service的启动、停止工作,事实证明确实是这样的。

那么IApplicationThread的实现者是谁呢?是ActivityThread类里面的一个内部类ApplicationThread类,我们看一下这个类

public class ApplicationThread extends ApplicationThreadNative {
public static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s";
public static final String ONE_COUNT_COLUMN = "%17s %8d";
public static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d";
public static final String TWO_COUNT_COLUMNS_DB = "%20s %8d %20s %8d";
public static final String DB_INFO_FORMAT = " %8d %8d %14d %s";
public static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1;

public ApplicationThread() {
}

...//code

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
int procState, Bundle state, PersistableBundle persistentState,
List pendingResults, List pendingNewIntents,
boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {

        updateProcessState(procState, false);

        ActivityClientRecord r = new ActivityClientRecord();

        r.token = token;
        r.ident = ident;
        r.intent = intent;
        r.referrer = referrer;
        r.voiceInteractor = voiceInteractor;
        r.activityInfo = info;
        r.compatInfo = compatInfo;
        r.state = state;
        r.persistentState = persistentState;

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

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

        r.profilerInfo = profilerInfo;

        r.overrideConfig = overrideConfig;
        updatePendingConfiguration(curConfig);

        sendMessage(H.LAUNCH_ACTIVITY, r);
    }

...//code
public void printRow(PrintWriter pw, String format, Object... objs) {
pw.println(String.format(format, objs));
}
}
}

咱们拿出scheduleLaunchActivity这个方法,ActivityStackSupervisor类中的realStartActivityLocked方法调用的次方法,可以看出调用了 sendMessage(H.LAUNCH_ACTIVITY, r);方法

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
int procState, Bundle state, PersistableBundle persistentState,
List pendingResults, List pendingNewIntents,
boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {

        updateProcessState(procState, false);

        ActivityClientRecord r = new ActivityClientRecord();

        r.token = token;
        r.ident = ident;
        r.intent = intent;
        r.referrer = referrer;
        r.voiceInteractor = voiceInteractor;
        r.activityInfo = info;
        r.compatInfo = compatInfo;
        r.state = state;
        r.persistentState = persistentState;

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

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

        r.profilerInfo = profilerInfo;

        r.overrideConfig = overrideConfig;
        updatePendingConfiguration(curConfig);

        sendMessage(H.LAUNCH_ACTIVITY, r);
    }

继续查看sendMessage()方法

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
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;  
    if (async) {  
        msg.setAsynchronous(true);  
    }  
    mH.sendMessage(msg);  

}
上面使用了Handler机制,来看一下H$handleMessage源码。

private class H extends Handler {

//...code  
public void handleMessage(Message msg) {  
        if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));  
        switch (msg.what) {  
            case LAUNCH_ACTIVITY: {  
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");  
                final ActivityClientRecord r = (ActivityClientRecord) msg.obj;  
                r.packageInfo = getPackageInfoNoCheck(  
                        r.activityInfo.applicationInfo, r.compatInfo);  
                handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");  
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
            } break;  

//...code  

}
当接受到消息后,最终调用ActivityThread$handleLaunchActivity方法启动Activity。

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
//...

Activity a = performLaunchActivity(r, customIntent);  

//...  

if (a != null) {  
    //...  

    handleResumeActivity(r.token, false, r.isForward,  
                !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);  

    //...  

} else {  
    // If there was an error, for any reason, tell the activity manager to stop us.  
    try {  
         ActivityManager.getService()  
                .finishActivity(r.token, Activity.RESULT_CANCELED, null,  
                        Activity.DONT_FINISH_TASK_WITH_ACTIVITY);  
        } catch (RemoteException ex) {  
            throw ex.rethrowFromSystemServer();  
        }  
}  

}

正文到此结束
本文目录