1.简述:
ActivityManagerService是系统的引导服务,应用程序的启动、切换、调度和四大组件的启动和管理都需要AMS的支持
2.Zygote是什么
Zygote进程是Android层面第一个进程(第一个art虚拟机),俗称进程孵化器,android中所有的进程都是通过 Zygote 分裂(fork)出来的
zygote启动-->初始化AndroidRuntime并且启动Runtime 启动Runtime主要做了三件事:
1.创建虚拟机
2.注册jni
3.使用jni调用ZygoteInit.Java的main方法
//native层
void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote){
jni_invocation.Init(NULL);
JNIEnv* env;
//启动虚拟机
if (startVm(&mJavaVM, &env, zygote, primary_zygote) != 0) {
return;
}
//注册jni 和java层通信
if (startReg(env) < 0) {
ALOGE("Unable to register all android natives\n");
return;
}
char* slashClassName = toSlashClassName(className != NULL ? className : "");
jclass startClass = env->FindClass(slashClassName);
......
//调用了zygoteInit的main方法
env->CallStaticVoidMethod(startClass, startMeth, strArray);
}
3.进入java世界先执行zygoteInit.main方法
1.创建 ZygoteServer,ZygoteServer作用是用来创建 Socket ,用来接收创建(fork)子进程的命令
- forkSystemServer方法内部是调用Zygote.forkSystemServer方法创建SystemServer进程,并且返回一个pid 当pid=0的时候 说明是SystemServer进程(pid会返回两次的 pid大于0的时候说明是Zygote进程)
3.第一次run是null 第二次的时候通过run方法执行MethodAndArgsCaller.run方法
@UnsupportedAppUsage
public static void main(String[] argv) {
ZygoteServer zygoteServer = null;
......
Runnable caller;
try {
......
//创建一个ZygoteServer对象
zygoteServer = new ZygoteServer(isPrimaryZygote);
if (startSystemServer) {
//fork一个SystemServer进程
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
if (r != null) {
r.run();//调用了MethodAndArgsCaller.run方法
return;
}
}
caller = zygoteServer.runSelectLoop(abiList);
} catch (Throwable ex) {
throw ex;
} finally {
if (zygoteServer != null) {
zygoteServer.closeServerSocket();
}
}
......
if (caller != null) {
caller.run();
}
}
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
......
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);
}
}
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
......
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mDisabledCompatChanges,
parsedArgs.mRemainingArgs, cl);
}
ZygoteInit.java
public static Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
......
return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
classLoader);
}
RuntimeInit.java
protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
protected static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
return new MethodAndArgsCaller(m, argv);
}
static class MethodAndArgsCaller implements Runnable {
/** method to call */
private final Method mMethod;
/** argument array */
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);
}
}
}
4.SystemServer.main方法
createSystemContext()
startBootstrapServices(t);
startCoreServices(t);
startOtherServices(t);
1.执行createSystemContext创建ContextImpl 然后创建一个Application
2.执行startBootstrapServices启动系统引导服务,ATM的启动 AMS的启动 PMS的启动 PKMS的启动等等
主要注意的是ActivityTaskManagerService是Android10加入的,ActivityTaskManagerService是用来管理activity声明周期的,在以前Android10以前都是AMS来管理的
3.执行startCoreServices启动核心服务
4.执行startOtherServices启动一些其他服务和Launcher
public static void main(String[] args) {
new SystemServer().run();
}
private void run(){
......
createSystemContext();创建系统上下文
mSystemServiceManager = new SystemServiceManager(mSystemContext);//创建SystemServiceManager
startBootstrapServices(t);
startCoreServices(t);
startOtherServices(t);
}
private void createSystemContext() {
//执行ActivityThread.systemMain方法
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
ActivityThread.java
public static ActivityThread systemMain() {
ThreadedRenderer.initForSystemProcess();
ActivityThread thread = new ActivityThread();
thread.attach(true, 0);
return thread;
}
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mConfigurationController = new ConfigurationController(this);
mSystemThread = system;
if (!system) {
......
} else {
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
//创建一个Context环境
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
//创建一个Application
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
......
}
}
ViewRootImpl.addConfigCallback(configChangedCallback);
}
5.startBootstrapServices:如何启动AMS的?
1.通过反射拿到ActivityTaskManagerService和ActivityManagerService对象来启动
2.ActivityTaskManager:Activity,Service等与ATMS跨进程交互的接口
SystemServer.java
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
......
//通过反射拿到ActivityTaskManagerService对象
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
//创建ActivityManagerService对象,并且把mSystemServiceManager和atm传给了ActivityManagerService
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
}
Lifecycle是ActivityTaskManagerService的内部类
ActivityTaskManagerService.Lifecycle.java
public static final class Lifecycle extends SystemService {
private final ActivityTaskManagerService mService;
public Lifecycle(Context context) {
super(context);
mService = new ActivityTaskManagerService(context);//创建activity的生命周期管理类
}
public ActivityTaskManagerService(Context context) {
......
mSystemThread = ActivityThread.currentActivityThread();
mUiContext = mSystemThread.getSystemUiContext();
mLifecycleManager = new ClientLifecycleManager();//在这里创建activity生命周期管理类
mInternal = new LocalService();
......
}
//创建完ActivityTaskManagerService之后 然后执行startService
@Override
public void onStart() {
//建立一个Binder 重点参数ACTIVITY_TASK_SERVICE后面会用到
publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
mService.start();
}
private void start() {
//LocalServices是一个ArrayMap
LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
}
//两个参数调用三个参数
protected final void publishBinderService(@NonNull String name, @NonNull IBinder service) {
publishBinderService(name, service, false);
}
//三个参数调用四个参数的
protected final void publishBinderService(@NonNull String name, @NonNull IBinder service,boolean allowIsolated) {
publishBinderService(name, service, allowIsolated, DUMP_FLAG_PRIORITY_DEFAULT);//注册Binder服务的
}
//把Binder存到ServiceManager里面取
protected final void publishBinderService(String name, IBinder service,
boolean allowIsolated, int dumpPriority) {
ServiceManager.addService(name, service, allowIsolated, dumpPriority);
}
//需要注意的是Context.ACTIVITY_TASK_SERVICE和上面的publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService)是一样的参数
ActivityTaskManager.java
//当我们需要用Binder通信的是只需ActivityTaskManager.getService方法
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
new Singleton<IActivityTaskManager>() {
@Override
protected IActivityTaskManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
return IActivityTaskManager.Stub.asInterface(b);
}
};
回到ActivityManagerService.Lifecycle.startService
ActivityManagerService.Lifecycle.java
public static ActivityManagerService startService(
SystemServiceManager ssm, ActivityTaskManagerService atm) {
sAtm = atm;
//执行SystemServiceManager.startService方法
return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}
@Override
public void onStart() {
mService.start();
}
......
public ActivityManagerService getService() {
return mService;
}
}
SystemServiceManager.java
public <T extends SystemService> T startService(Class<T> serviceClass) {
//注意传进来的参数是ActivityManagerService.Lifecycle.class
try {
final String name = serviceClass.getName();
......
final T service;
try {
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);//在这里初始化ActivityManagerService.Lifecycle
} catch (InstantiationException ex) {
......
}
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public Lifecycle(Context context) {
super(context);
mService = new ActivityManagerService(context, sAtm);
}
6.AMS启动的时候做了那些操作:
1.初始化广播
2.发布电池状态服务
ActivityManagerService.java
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
//前台广播,10s
final BroadcastConstants foreConstants = new BroadcastConstants(
Settings.Global.BROADCAST_FG_CONSTANTS);
foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
//后台广播,60s
final BroadcastConstants backConstants = new BroadcastConstants(
Settings.Global.BROADCAST_BG_CONSTANTS);
backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
//分流广播,60s
final BroadcastConstants offloadConstants = new BroadcastConstants(
Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
// by default, no "slow" policy in this queue
offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
mEnableOffloadQueue = SystemProperties.getBoolean(
"persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);
//前台广播队列
mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
"foreground", foreConstants, false);
//后台广播队列
mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
"background", backConstants, true);
//分流广播队列
mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
"offload", offloadConstants, true);
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;
mBroadcastQueues[2] = mOffloadBroadcastQueue;
}
startOtherServices:启动一些其他服务和Launcher
1、进程存在,start 启动 activity
2、进程不存在,lunch 启动 activity
startOtherServices的有兴趣的参考:https://www.jianshu.com/p/1c828bf5dd13
总结:
1.Zygote创建虚拟机
2.注册jni
3.使用jni调用ZygoteInit.Java的main方法
4.创建ZygoteServer方法 ZygoteServer本质上是一个Socket,用来接收创建(fork)子进程的命令
5.forkSystemServer进程 执行SystemServer.main方法
6.SystemServer先执行createSystemContext方法 创建ContextImpl然后创建Application
7.执行startBootstrapServices 通过反射拿到ActivityTaskManagerService和ActivityManagerService对象
8.在ActivityTaskManagerService里面会执行ClientLifecycleManager用来管理activity生命周期,然后执行ActivityTaskManagerService内部类Lifecycle的onStart方法
9.ATMS内部类Lifecycle的onStart方法会建立一个Binder
10.在ActivityTaskManager.getService方法可以到这个Binder
11.ActivityManagerService构造方法里面会初始化广播等相关操作