AMS(ActivityManagerService) 在 Android 中占据着非常重要的地位,它是 Framework 核心服务之一,负责四大组件的统一调度。同时,AMS 也管理着进程、电池、内存及权限。 注:文中源码来源于 Android API 30
Zygote 进程 Zygote 为受精卵的意思,由名称可以看得出来,Zegote 进程的主要作用就是分裂(fork)进程。
Zygote 的启动流程 app_main.cpp -> main()
-> 初始化 AndroidRuntime -> runtime.start()
->
AndroidRuntime.start()
startVM()
启动虚拟机 从上述流程可以看出,一个进程包裹了一个虚拟机。
startReg()
注册 JNI
env -> CallStaticVoidMethod()
-> ZygoteInit.main()
通过 JNI 调用 ZygoteInit.main()
进入到 Java 层。
ZygoteInit.main() public class ZygoteInit { public static void main (String argv[]) { if (!enableLazyPreload) { preload(bootTimingsTraceLog); } zygoteServer = new ZygoteServer (isPrimaryZygote); if (startSystemServer) { Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer); if (r != null ) { r.run(); return ; } } caller = zygoteServer.runSelectLoop(abiList); } }
ZygoteInit.main()
主要做了以下几个事情:
预加载
创建 Socket 为什么不用 Binder?
Binder 还没有初始化完成。
Binder 是多线程机制,fork 时容易死锁。
fork SystemServer 进程
如果返回的 Runnable 不为空则通过反射执行 SystemServer.main()
方法。
如果返回的 Runnable 为空则标识当前进程为父进程,也就是 Zygote 进程,接着就会执行第四步进行循环等待。
等待 AMS 消息,创建线程
SystemServer 进程 SystemServer 进程是 zygote 进程第一个 fork 出来的进程,AMS、WMS 以及 PMS 等都是由 SystemServer 进程启动的。 我们进入 ZygoteInit.forkSystemServer()
看一下 SystemServer 进程的创建过程:
private static Runnable forkSystemServer (String abiList, String socketName, ZygoteServer zygoteServer) { try { pid = Zygote.forkSystemServer( parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids, parsedArgs.mRuntimeFlags, null , parsedArgs.mPermittedCapabilities, parsedArgs.mEffectiveCapabilities); } catch (IllegalArgumentException ex) { throw new RuntimeException (ex); } if (pid == 0 ) { if (hasSecondZygote(abiList)) { waitForSecondaryZygote(socketName); } zygoteServer.closeServerSocket(); return handleSystemServerProcess(parsedArgs); } return null ; }
下边我们经过 ZygoteInit.handleSystemServerProcess()
-> ZygoteInit.zygoteInit()
-> RuntimeInit.applicationInit()
-> RuntimeInit.findStaticMain()
这几个方法的调度,进入了 RuntimeInit.findStaticMain()
方法:
public class RuntimeInit { protected static Runnable findStaticMain (String className, String[] argv, ClassLoader classLoader) { Class<?> cl; try { cl = Class.forName(className, true , classLoader); } catch (ClassNotFoundException ex) { throw new RuntimeException ( "Missing class when invoking static main " + className, ex); } Method m; try { m = cl.getMethod("main" , new Class [] { String[].class }); } catch (NoSuchMethodException ex) { throw new RuntimeException ( "Missing static main on " + className, ex); } catch (SecurityException ex) { throw new RuntimeException ( "Problem getting static main on " + className, ex); } int modifiers = m.getModifiers(); if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) { throw new RuntimeException ( "Main method is not public and static on " + className); } return new MethodAndArgsCaller (m, argv); } static class MethodAndArgsCaller implements Runnable { private final Method mMethod; private final String[] mArgs; public MethodAndArgsCaller (Method method, String[] args) { mMethod = method; mArgs = args; } public void run () { try { mMethod.invoke(null , new Object [] { mArgs }); } catch (IllegalAccessException ex) { throw new RuntimeException (ex); } catch (InvocationTargetException ex) { Throwable cause = ex.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof Error) { throw (Error) cause; } throw new RuntimeException (ex); } } } }
findStaticMain()
返回一个 MethodAndArgsCaller 对象,而 MethodAndArgsCaller 是一个 Runnable 最终在 ZygoteInit.main()
中执行。 下面我们进入到 SystemServer.main()
-> run()
方法看一下:
private void run () { createSystemContext(); ActivityThread.initializeMainlineModules(); mSystemServiceManager = new SystemServiceManager (mSystemContext); startBootstrapServices(t); startCoreServices(t); startOtherServices(t); Looper.loop(); }
startBootstrapServices() 接着进入到 startBootstrapServices()
方法,看下 AMS 的启动:
private void startBootstrapServices (@NonNull TimingsTraceAndSlog t) { ActivityTaskManagerService atm = mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService(); mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); mActivityManagerService.setSystemProcess(); }
ActivityTaskManagerService
创建 Activity 生命周期管理类 ClientLifecycleManager
publishBinderService()
-> ServiceManager.addServer()
将 ATM 服务保存到 ServiceManager 中
ActivityManagerService 的创建
ActivityManagerService.setSystemProcess()
将 AMS 保存到 ServiceManager
startOtherServices() private void startOtherServices (@NonNull TimingsTraceAndSlog t) { wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore, new PhoneWindowManager (), mActivityManagerService.mActivityTaskManager); ServiceManager.addService(Context.WINDOW_SERVICE, wm, false , DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO); mActivityManagerService.setWindowManager(wm); mActivityManagerService.systemReady(() -> { }, t); }
在 startOtherServices()
函数中可以看到启动了很多服务,其中就有 WMS,最后调用应用的启动 systemReady()
方法 。
ActivityManagerService ActivityManagerService 的创建 在 ActivityManagerService.Lifecycle 类的构造方法中创建了 ActivityManagerService 对象
public static final class Lifecycle extends SystemService { private final ActivityManagerService mService; private static ActivityTaskManagerService sAtm; public Lifecycle (Context context) { super (context); mService = new ActivityManagerService (context, sAtm); } public static ActivityManagerService startService (SystemServiceManager ssm, ActivityTaskManagerService atm) { sAtm = atm; return ssm.startService(ActivityManagerService.Lifecycle.class).getService(); } }
进入 ActivityManagerService 的构造方法看下:
public ActivityManagerService (Context systemContext, ActivityTaskManagerService atm) { mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, DisplayThread.get().getLooper()); }
其中关键的部分是调用 ATM 的初始化
public class ActivityTaskManagerService extends IActivityTaskManager .Stub { public void initialize (IntentFirewall intentFirewall, PendingIntentController intentController, Looper looper) { mStackSupervisor = createStackSupervisor(); setRecentTasks(new RecentTasks (this , mStackSupervisor)); } }
启动页面 ActivityManagerService.systemReady()
对 Activity 启动的管理
Activity.startActivity()
-> Instrumentation.execStartActivity()
public class Instrumentation { public ActivityResult execStartActivity ( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { try { intent.migrateExtraStreamToClipData(who); intent.prepareToLeaveProcess(who); 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 ; } }
通过 ServiceManager 获取 ATM 服务,并调用 ATM 服务的 startActivity()
方法启动 Activity。 扩展:ActivityTaskManager.getService()
用到了代理模式。
下面我们看一下 startActivity()
的调用链:
-> ActivityTaskManagerService.startActivity() -> ActivityTaskManagerService.startActivityAsUser() -> ActivityStarter.startActivityUnchecked() -> ActivityStarter.startActivityInner() -> RootWindowContainer.resumeFocusedStacksTopActivities() -> ActivityStack.resumeFocusedStacksTopActivities() -> ActivityStack.resumeTopActivityInnerLocked() -> ActivityStackSupervisor.startSpecificActivity()
后边比较关键的是 ActivityStackSupervisor.startSpecificActivity()
方法:
void startSpecificActivity (ActivityRecord r, boolean andResume, boolean checkConfig) { 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); } knownToBeDead = true ; } r.notifyUnknownVisibilityLaunchedForKeyguardTransition(); final boolean isTop = andResume && r.isTopRunningActivity(); mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity" ); }
进入到 startSpecificActivity()
方法,
如果进程未启动,则用 Socket 通知 Zygote fork 应用的进程,然后用反射的方式调用 ActivityThread.main()
方法。 进入 main()
方法后会执行 attach()
方法,此时传入的 system 参数为 false
,可以看出 ActivityThread 通过快进程(Binder)的方式将 ActivityThread 传给 AMS。public final class ActivityThread extends ClientTransactionHandler { public static void main (String[] args) { ActivityThread thread = new ActivityThread (); thread.attach(false , startSeq); } private void attach (boolean system, long startSeq) { if (!system) { RuntimeInit.setApplicationObject(mAppThread.asBinder()); final IActivityManager mgr = ActivityManager.getService(); mgr.attachApplication(mAppThread, startSeq); } else { } } }
如果应用程序已启动,则调用 realStartActivityLocked()
方法,执行 Activity 的生命周期。
AMS 如何管理新的进程的 Activity 的生命周期
boolean realStartActivityLocked (ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) throws RemoteException { final ClientTransaction clientTransaction = ClientTransaction.obtain( proc.getThread(), r.appToken); final DisplayContent dc = r.getDisplay().mDisplayContent; clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent (r.intent), System.identityHashCode(r), r.info, mergedConfiguration.getGlobalConfiguration(), mergedConfiguration.getOverrideConfiguration(), r.compat, r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(), r.getSavedState(), r.getPersistentSavedState(), results, newIntents, dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(), r.assistToken, r.createFixedRotationAdjustmentsIfNeeded())); final ActivityLifecycleItem lifecycleItem; if (andResume) { lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward()); } else { lifecycleItem = PauseActivityItem.obtain(); } mService.getLifecycleManager().scheduleTransaction(clientTransaction); }
接着就会调用 ClientLifecycleManager.scheduleTransaction()
方法:
-> ClientLifecycleManager.scheduleTransaction() -> ClientTransaction.schedule() -> IApplicationThread.scheduleTransaction() -> ActivityThread.ApplicationThread.scheduleTransaction() -> ActivityThread.scheduleTransaction() -> ActivityThread.H.handleMessage() -> msg=EXECUTE_TRANSACTION => TransactionExecutor.excute() -> executeCallbacks() => LaunchActivityItem -> executeLifecycleState() => state=ON_START & state=ON_RESUME
面试题 为什么使用 Zygote fork 应用进程,而不是用 Init 或者 SystemServer?
虚拟机的启动是在 Zygote 进程的,在 Init 进程虚拟机还没有启动;Init 进程除了启动 Zygote 进程,还会启动的一些其他进程,而这些进程与应用进程不相关。
SystemServer 会启动 AMS、WMS、PMS 等很多系统服务,这些服务是所有的应用进程公用的。
SystemServiceManager 和 ServiceManager 的区别
SystemServiceManager 是专门用来管理 SystemService 的生命周期的,例如 ActivityManagerService.Lifecycle 和 ActivityTaskManagerService.Lifecycle 等。
ServiceManager 是用来管理系统服务的,ServiceManager 通过 addService()
方法添加服务,通过 getService()
获取服务。
如何启动一个未注册的 Activity(插件化原理)
https://www.jianshu.com/p/4fc77fbac938 https://woaitqs.cc/2016/08/17/2016-08-17-launch-activity-without-registering-in-manifest/
首先在 AndroidManifest 中注册一个占位的 Activity
在启动 Activity 的地方中的 Intent 里边的目标 Activity 替换为占位 Activity
寻找合适的 hook 点,在 ActivityThread 启动 Activity 的时候,再将占位的 Activity 替换为目标 Activity。