IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> 【Android 源码学习】SystemServer启动原理 -> 正文阅读

[移动开发]【Android 源码学习】SystemServer启动原理

Android 源码学习 SystemServer启动原理

望舒课堂 SystemServer进程启动原理学习记录整理。
参考文章:
Android系统启动流程(三)解析SyetemServer进程启动过程

SystemServer简介

SystemServer是Android系统的核心之一,大部分Android提供的服务都在该进程中。

Zygote处理SystemServer进程

zygote处理SystemServer时序图

ZygoteInit AppRuntime RuntimeInit MethodAndArgsCaller SystemServer main forkSystemServer handleSystemServerProcess zygoteInit onZygoteInit applicationInit findStaticMain new new zygoteInit调用回调的run run main ZygoteInit AppRuntime RuntimeInit MethodAndArgsCaller SystemServer

ZygoteInit.java

/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
zygoteInit的关键代码:

	private static Runnable forkSystemServer(String abiList, String socketName,
	            ZygoteServer zygoteServer) {
		......
		  /* Request to fork the system server process */
            // 创建子进程(SystemServer进程)
            pid = Zygote.forkSystemServer(
                    parsedArgs.mUid, parsedArgs.mGid,
                    parsedArgs.mGids,
                    parsedArgs.mRuntimeFlags,
                    null,
                    parsedArgs.mPermittedCapabilities,
                    parsedArgs.mEffectiveCapabilities);
                    ......
                    /* For child process */
        // 当前代码逻辑运行在子进程中
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }

         zygoteServer.closeServerSocket();
         // 处理SystemServer进程
         return handleSystemServerProcess(parsedArgs);
         ......
	}

  private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
	  	 if (parsedArgs.mInvokeWith != null) {
	  	 	......
	  	 } else {
  	 		ClassLoader cl = null;
            if (systemServerClasspath != null) {
            	// 加载系统类
                cl = createPathClassLoader(systemServerClasspath, parsedArgs.mTargetSdkVersion);

                Thread.currentThread().setContextClassLoader(cl);
            }

            /*
             * Pass the remaining arguments to SystemServer.
             */
            return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
                    parsedArgs.mDisabledCompatChanges,
                    parsedArgs.mRemainingArgs, cl);
  	 }
  	 public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
            String[] argv, ClassLoader classLoader) {
        if (RuntimeInit.DEBUG) {
            Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
        }

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
        RuntimeInit.redirectLogStreams();

        RuntimeInit.commonInit();
        // 启动Binder线程池
        ZygoteInit.nativeZygoteInit();
        // 进入SystemServer的main方法
        return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
                classLoader);
    }
	private static final native void nativeZygoteInit();
  }

nativeZygoteInit();调用的是native方法,位于AppRuntime
/frameworks/base/core/jni/AndroidRuntime.cpp


int register_com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env)
{
	/**
	* JNINativeMethod 是在/libnativehelper/include_jni/jni.h 中定义的struct 
	* typedef struct {
	*     const char* name;    //java方法名
	*     const char* signature;//java方法签名信息
	*     void*       fnPtr;//java方法在JNI中对应的函数
	* } JNINativeMethod;
	*/
    const JNINativeMethod methods[] = {
        { "nativeZygoteInit", "()V",
            (void*) com_android_internal_os_ZygoteInit_nativeZygoteInit },
    };
    return jniRegisterNativeMethods(env, "com/android/internal/os/ZygoteInit",
        methods, NELEM(methods));
}
static AndroidRuntime* gCurRuntime = NULL;
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
    gCurRuntime->onZygoteInit();
}
	onZygoteInit 是虚方法 具体实现在AndroidRuntime的子类AppRuntime中

/frameworks/base/core/jni/include/android_runtime/AndroidRuntime.h

/**
     * This gets called after the JavaVM has initialized after a Zygote
     * fork. Override it to initialize threads, etc. Upon return, the
     * correct static main will be invoked.
     */
    virtual void onZygoteInit() { }

具体代码还是在app_main中
/frameworks/base/cmds/app_process/app_main.cpp

class AppRuntime : public AndroidRuntime{
	......
	virtual void onZygoteInit()
    {
        sp<ProcessState> proc = ProcessState::self();
        ALOGV("App process: starting thread pool.\n");
        // 启动binder线程池
        proc->startThreadPool();
    }
	......
}

RuntimeInit.java

/frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
ZygoteInit.zygoteInit 方法 返回RuntimeInit.applicationInit

    protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
            String[] argv, ClassLoader classLoader) {
        ......
        // Remaining arguments are passed to the start class's static main
        return findStaticMain(args.startClass, args.startArgs, classLoader);
    }
	protected static Runnable findStaticMain(String className, String[] argv,
            ClassLoader classLoader) {
        Class<?> cl;

        try {
        	// 反射得到SystemServer类
            cl = Class.forName(className, true, classLoader);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Missing class when invoking static main " + className,
                    ex);
        }

        Method m;
        try {
        	// 获取 main 方法
            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);
        }

        /*
         * This throw gets caught in ZygoteInit.main(), which responds
         * by invoking the exception's run() method. This arrangement
         * clears up all the stack frames that were required in setting
         * up the process.
         */
        return new MethodAndArgsCaller(m, argv);
    }
    /**
     * Helper class which holds a method and arguments and can call them. This is used as part of
     * a trampoline to get rid of the initial process setup stack frames.
     */
    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 {
            	// 调用SystemServer的main方法
                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);
            }
        }
    }

ZygoteInit 执行回调

/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

 public static void main(String argv[]) {
 	......
  	zygoteServer = new ZygoteServer(isPrimaryZygote);

    if (startSystemServer) {
    	//fock SystemServer进程
		Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);

		// {@code r == null} in the parent (zygote) process, and {@code r != null} in the
		// child (system_server) process.
		if (r != null) {
			r.run();//执行system_server
			return;
		}
		 Log.i(TAG, "Accepting command socket connections");

            // The select loop returns early in the child process after a fork and
            // loops forever in the zygote.
            // 轮询,等待AMS请求
            caller = zygoteServer.runSelectLoop(abiList);
        } catch (Throwable ex) {
            Log.e(TAG, "System zygote died with exception", ex);
            throw ex;
        } finally {
            if (zygoteServer != null) {
                zygoteServer.closeServerSocket();
            }
        }

        // We're in the child process and have exited the select loop. Proceed to execute the
        // command.
        if (caller != null) {
            caller.run();
        }
	}
 }

解析SystemServer进程

/frameworks/base/services/java/com/android/server/SystemServer.java

经过ZygoteInit启动SystemServer启动,进入SystemServer的main方法
关键方法:

 public static void main(String[] args) {
        new SystemServer().run();
 }
 private void run() {
 	......
 	  // Create the system service manager.
            mSystemServiceManager = new SystemServiceManager(mSystemContext);
            mSystemServiceManager.setStartInfo(mRuntimeRestart,
                    mRuntimeStartElapsedTime, mRuntimeStartUptime);
            //将Service保存在本进程中,保存的Service在同一进程
            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
            ......
            // Start services.
        try {
            t.traceBegin("StartServices");
            // 启动引导服务
            startBootstrapServices(t);
            // 启动核心服务
            startCoreServices(t);
            // 启动其他服务
            startOtherServices(t);
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            t.traceEnd(); // StartServices
        }
        ......
 }

系统服务

列举部分系统服务。
表格截取刘望舒的文章。

| centered 文本居中 | right-aligned 文本居右 |

引导服务作用
Installer系统安装apk时的一个服务类,启动完成Installer服务之后才能启动其他的系统服务
ActivityManagerService负责四大组件的启动、切换、调度。
PowerManagerService计算系统中和Power相关的计算,然后决策系统应该如何反应
LightsService管理和显示背光LED
DisplayManagerService用来管理所有显示设备
UserManagerService多用户模式管理
SensorService为系统提供各种感应器服务
PackageManagerService用来对apk进行安装、解析、删除、卸载等等操作
核心服务作用
BatteryService管理电池相关的服务
UsageStatsService收集用户使用每一个APP的频率、使用时常
WebViewUpdateServiceWebView更新服务
其他服务作用
CameraService摄像头相关服务
AlarmManagerService全局定时器管理服务
InputManagerService管理输入事件
WindowManagerService窗口管理服务
VrManagerServiceVR模式管理服务
BluetoothService蓝牙管理服务
NotificationManagerService通知管理服务
DeviceStorageMonitorService存储相关管理服务
LocationManagerService定位管理服务
AudioService音频相关管理服务

SystemServiceManager.java

SystemServer里调用SystemServiceManager的startService来启动相应服务
例如DisplayManagerService

// Display manager is needed to provide display metrics before package manager
        // starts up.
        t.traceBegin("StartDisplayManager");
        mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
        t.traceEnd();

SystemServiceManager

/frameworks/base/services/core/java/com/android/server/SystemServiceManager.java

关键代码:

public void startService(@NonNull final SystemService service) {
        // Register it.
        mServices.add(service);
        // Start it.
        long time = SystemClock.elapsedRealtime();
        try {
            service.onStart();
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + service.getClass().getName()
                    + ": onStart threw an exception", ex);
        }
        warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}

总结

SystemServer进程被创建后,主要做了如下工作:

  1. 启动Binder线程池,这样就可以与其他进程进行通信
  2. 创建SystemServiceManager用于对系统的服务创建、启动和生命周期管理。
  3. 启动各种系统服务
  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-11-05 00:39:30  更:2022-11-05 00:42:09 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/19 21:37:05-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码