当前位置:   article > 正文

Activity启动流程分析(android-29)(1)_android activity流程

android activity流程

======

1. binder机制简介

binder是进程间通信的一种方式。在操作系统中,分为内核空间和用户空间,每个app都运行在自己的用户空间,binder机制底层正是两个app进程通过共享内核内存区域实现的;具体实现不做深入分析;
在binder机制中,进行进程通信的两方,可分别称他们为Cient进程和Server进程;Cient进程和Server进程是由具体场景而定的,一个进程即可以是Cient进程,也可以是Server进程。

2. ServiceManager

ServiceManager负责把Binder Server注册到一个容器中,这样当有Client进程想与Server进程通信时,ServiceManager就可以从查找表中找到Binder Server,并返回Binder Server的代理对象给Client进程。

3. ActivityManagerService

ActivityManagerService是一个系统服务进程,四大组件的启动方式都是通过binder的方式与ActivityManagerService通信完成的;
ActivityManagerService将自己注册到ServiceManager的代码如下(本文分析基于android-29源码):

public class ActivityManagerService extends IActivityManager.Stub {
public void setSystemProcess() {
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
}
}

注册完成之后,其他进程就可通过如下方式获得ActivityManagerService的代理:

public class ActivityManager {
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
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;
}
};
}

以上代码,可以看出ActivityManager封装了对ActivityManagerService的调用,通过ActivityManager.gerService()即可获得对ActivityManagerService的调用。

4. ActivityThread、ApplicationThread傻傻分不清楚

ActivityThread就是UI线程,是在APP启动时创建的;它包含一个static的main()方法如下所示(后面会详细分析):

public final class ActivityThread{
// 后面会重点分析
Instrumentation mInstrumentation;

public static void main(String[] args) {
// 省略部分代码…
Looper.prepareMainLooper();
// …
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
// …
Looper.loop();
}

private void attach(boolean system, long startSeq) {
mInstrumentation = new Instrumentation();
// …
mInstrumentation.basicInit(this);
ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
}
}

ApplicationThread是ActivityThread的内部类,并不是一个线程,可用来代表当前APP进程(可能这就是它叫Thread的原因吧),由以下代码可分析出app间进程通信时,获得另一个app进程也是通过binder来获取其代理实现的;

private class ApplicationThread extends IApplicationThread.Stub {
// 省略部分代码…
}

5. Instrumentation

instrumentation
英 [ˌɪnstrəmenˈteɪʃn] 美 [ˌɪnstrəmenˈteɪʃn]
n.(一套)仪器,仪表;器乐谱写

Instrumentation源码解释如下:

/**

  • Base class for implementing application instrumentation code. When running
  • with instrumentation turned on, this class will be instantiated for you
  • before any of the application code, allowing you to monitor all of the
  • interaction the system has with the application. An Instrumentation
  • implementation is described to the system through an AndroidManifest.xml’s
  • <instrumentation> tag.
    */

可以大概理解为所有与application有关的调用都会通过Instrumentation这样一个仪器来方便地观察到;换句话说就是,所有有关application的调用实际上都会通过Instrumentation;看一下其源码就可以看到它里面完成了许多功能:

public class Instrumentation {
private ActivityThread mThread = null;
private MessageQueue mMessageQueue = null;
private List mActivityMonitors;

public Application newApplication(ClassLoader cl, String className, Context context) {}

public Activity newActivity(ClassLoader cl, String className,
Intent intent) {}

public void callActivityOnNewIntent(Activity activity, Intent intent) {}

public ActivityResult execStartActivity(){}

}

二、Activity启动流程分析

例如App1要启动App2的一个Activity;Activity启动流程分析如下:

1. App1中的SampleActivity1启动App2的SampleActivity2

public class SampleActivity1 {
public void onClick() {
Intent intent = getPackageManager().getLaunchIntentForPackage(“com.app2.sample”);
startActivity(intent);
}
}

2. Activity源码分析

public class Activity {
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}

public void startActivity(Intent intent, @Nullable Bundle options) {
// …
startActivityForResult(intent, -1);
}

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
// 省略部分代码…
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());
}
}
}

可以看到,Activity的startActivity最终都调用到了Instrumentation里面;

3. Instrumentation源码分析

继续分析Instrumentation的execStartActivity()方法:

public class Instrumentation {
/**

  • 可以看到传递的参数中比较重要的几个:
    1. context who:就是前面的SampleActivity1
    1. IBinder contextThread:传的value是mMainThread.getApplicationThread(),即当前APP进程,这样AMS进程才可以通过IBinder与App1进程通信(比如将结果返回,就需要binder通信)
    1. IBinder token:又见IBinder,那一定也是别的进程需要通过这个IBinder进行通信
    1. Intent intent:启动参数
      **/
      public ActivityResult execStartActivity(
      Context who, IBinder contextThread, IBinder token, Activity target,
      Intent intent, int requestCode, Bundle options) {
      IApplicationThread whoThread = (IApplicationThread) contextThread;
      // 省略部分代码…
      try {
      int result = ActivityTaskManager.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;
      }
      }

可以看到,又继续调用到了ActivityTaskManager.getService().startActivity()里面。
ps. 在android-28源码中是调用到了ActivityManager.getService().startActivity()里面,更老版本android源码中是调用了ActivityManagerNative.getDefault(),原理都类似,都是调用返回一个代理,最终到了系统进程去执行后续调起逻辑。

4. ActivityTaskManager源码分析

@SystemService(Context.ACTIVITY_TASK_SERVICE)
public class ActivityTaskManager {
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}

private static final Singleton IActivityTaskManagerSingleton =
new Singleton() {
@Override
protected IActivityTaskManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
return IActivityTaskManager.Stub.asInterface(b);
}
};
}

可以看出,ActivityTaskManager.getService()调用得到IBinder的proxy继续执行后续代码,这样就就调用到了系统进程里面继续执行;ActivityTaskManager是系统启动期间就注册的一个binder service,其注册代码如下:

@SystemApi
public final class SystemServiceRegistry {
static {
registerService(Context.ACTIVITY_TASK_SERVICE, ActivityTaskManager.class,
new CachedServiceFetcher() {
@Override
public ActivityTaskManager createService(ContextImpl ctx) {
return new ActivityTaskManager(
ctx.getOuterContext(), ctx.mMainThread.getHandler());
}});
}

接下来继续分析系统进程中startActivity()的执行步骤;

5. ActivityTaskManagerService源码分析

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
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());
}

int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
boolean validateIncomingUser) {
// 省略部分代码…
// getActivityStartController().obtainStarter返回一个ActivityStarter对象,下面继续分析ActivityStarter
return getActivityStartController().obtainStarter(intent, “startActivityAsUser”)
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setMayWait(userId)
.execute();

}
}

6. ActivityStarter源码分析

ActivityStarter负责处理intent中flag、启动模式等参数;

class ActivityStarter {
int execute() {
try {
// …
return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
mRequest.outActivity, mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup,
mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
} finally {
onExecutionComplete();
}
}

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
int result = START_CANCELED;
final ActivityStack startedActivityStack;
try {
mService.mWindowManager.deferSurfaceLayout();
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
}
// …
}

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
// …
mRootActivityContainer.resumeFocusedStacksTopActivities();
}
}

接下里继续到RootActivityContainer;

/**

  • Root node for activity containers.
  • TODO: This class is mostly temporary to separate things out of ActivityStackSupervisor.java. The
  • intention is to have this merged with RootWindowContainer.java as part of unifying the hierarchy.
  • 看样子这个类后面可能会被合入到RootWindowContainer里,不重点分析;
    */
    class RootActivityContainer {
    boolean resumeFocusedStacksTopActivities(
    ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
    if (targetStack != null && (targetStack.isTopStackOnDisplay() || getTopDisplayFocusedStack() == targetStack)) {
    result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }
    }
    }

7. ActivityStack源码分析

ActivityStack负责管理activity栈和activity的状态,包括根据activity栈的状态决定如何管理activity等,当然activity的启动也是由它来继续完成;

/**

  • State and management of a single stack of activities.
    */
    class ActivityStack extends ConfigurationContainer {
    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
    if (mInResumeTopActivity) {
    // Don’t even start recursing.
    return false;
    }

boolean result = false;
try {
// Protect against recursion.
mInResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options);
}
}

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
// …
if (next.attachedToProcess()) {
if (nextNext != next) {
// Do over!
mStackSupervisor.scheduleResumeTopActivities();
}
} else {
// Whoops, need to restart this activity!
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
}
}

8. StackSupervisor源码分析

// TODO: This class has become a dumping ground. Let’s
// - Move things relating to the hierarchy to RootWindowContainer
// - Move things relating to activity life cycles to maybe a new class called ActivityLifeCycler
// - Move interface things to ActivityTaskManagerService.
// - All other little things to other files.
// 看样子这部分代码后面也会被RootWindowContainer里面,后面Android源码分析可能要重点分析这个类了

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/864182
推荐阅读
相关标签