Android Framework - 学习起步

计算机软件开发 2024-9-4 19:52:07 47 0 来自 中国
前言

作为一名合格的 Android 开发,必要学习 Framework 知识,来办理 App 稳固性干系的问题
Framework 的源码学习一样平常由 init.rc 开始看起,因为它是一个 Android 体系启动必备的紧张脚本,之后的几大体系进程都是由它启动的,比如 zygote,systemserver 等,这里紧张纪录一些根本概念,以及 Zygote 启动的源码分析
Binder 原理是相对较难的一个部分,先看其他体系源码,等功力富足时再拜读
init.rc

init 启动的四个紧张进程如下:

  • Zygote 创建 App 的进程
  • ServiceManager 负责c/s通讯管理的进程
  • SurfaceFlingler 体现渲染服务
  • Media 多媒体服务
SystemServer

Zygote 进程启动时,会顺带启动 SystemServer 进程
fork 是通过 native 方法调用,返回 pid 给到 Java 层
PMS

负责安装卸载 app,紧张用于剖析 apk 文件等操纵
fork 进程的理解

我们都知道新开启的 App 进程都是由 Zygote.fork 出来的,那 fork  到底是个什么操纵呢
Zygote进程和app进程fork过程分析
起首 fork 是叉子的意思,我们所提及的 fork 现实为 native 层的 fork() 函数,当实行该函数时,会对父进程举行一次拷贝,拷贝完成过后,但用户内存空间是相互独立,从如今开始,开始各走各的
fork() 调用一次,返回两次,这是特性
fork的原理及实现

  • AMS 和 Zygote 间是怎样通讯的
AMS 通过 Socket 来关照 Zygote 进程,发送过程是怎样的,可以看下这篇文章 fork 进程的过程
AMS -> Zygote 通过 socket 哀求,Zygote 调用 fork() 方法,乐成后返回给 AMS,新进程创建后调用 AtivityThread.main()
对于 epoll 的理解

全名是 EventPoll ,poll 是轮询的意思,是一个变乱关照机制,性能上比力好,Handler 底层的变乱叫醒也是用这玩意,具体是怎么实现的,不太清晰,先挖个坑,反面找个时间拜读一下源码
Zygote 启动过程

起首 Android 体系的第一个进程为 init 进程,负责剖析实行 init.rc ,而且启动了 Zygote 进程
接下来通过阅读源码,分析一下 Zygote 的启动过程,从 AndroidRuntime,cpp 的 start() 开始看起
void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote){    const char* rootDir = getenv("ANDROID_ROOT")    // 创建假造机    jni_invocation.Init(NULL);    JNIEnv* env;    if (startVm(&mJavaVM, &env, zygote, primary_zygote) != 0) {        return;    }    onVmCreated(env);     // 传入 ZygoteInit 的类路径    // 当火线程为假造机的主线程    char* slashClassName = toSlashClassName(className != NULL ? className : "");    jclass startClass = env->FindClass(slashClassName);    if (startClass == NULL) {        /* keep going */    } else {        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",            "([Ljava/lang/String;)V");        if (startMeth == NULL) {            /* keep going */        } else {            env->CallStaticVoidMethod(startClass, startMeth, strArray);#if 0            if (env->ExceptionCheck())                threadExitUncaughtException(env);#endif        }    }    //实行到这里假造机退出,应该对应着进程烧毁    free(slashClassName);    ALOGD("Shutting down VM\n");}通过 native 创建了假造机实例,然后通过 JNI 调用 ZygoteInit ,开始到 Java 层的逻辑了

  • Java 层
// ZygoteInit.class  public static void main(String[] argv) {        ZygoteServer zygoteServer = null;        // Mark zygote start. This ensures that thread creation will throw        // an error.        ZygoteHooks.startZygoteNoThreadCreation();        // Zygote goes into its own process group.        try {            Os.setpgid(0, 0);        } catch (ErrnoException ex) {            throw new RuntimeException("Failed to setpgid(0,0)", ex);        }        Runnable caller;        try {            // 开启 DDMMS             RuntimeInit.preForkInit();            boolean startSystemServer = false;            String zygoteSocketName = "zygote";            String abiList = null;            boolean enableLazyPreload = false;            // 判断各种设置开关            for (int i = 1; i < argv.length; i++) {                if ("start-system-server".equals(argv)) {                    startSystemServer = true;                } else if ("--enable-lazy-preload".equals(argv)) {                    enableLazyPreload = true;                } else if (argv.startsWith(ABI_LIST_ARG)) {                    abiList = argv.substring(ABI_LIST_ARG.length());                } else if (argv.startsWith(SOCKET_NAME_ARG)) {                    zygoteSocketName = argv.substring(SOCKET_NAME_ARG.length());                } else {                    throw new RuntimeException("Unknown command line argument: " + argv);                }            }            // 判断 SocketName 是否为 "zygote"            final boolean isPrimaryZygote = zygoteSocketName.equals(Zygote.PRIMARY_SOCKET_NAME);            if (!isRuntimeRestarted) {                if (isPrimaryZygote) {                    FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,                            BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__ZYGOTE_INIT_START,                            startTime);                }                                 // 判断 SocketName 是否为 "zygote_secondary"                else if (zygoteSocketName.equals(Zygote.SECONDARY_SOCKET_NAME)) {                    FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,                            BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SECONDARY_ZYGOTE_INIT_START,                            startTime);                }            }            if (abiList == null) {                throw new RuntimeException("No ABI list supplied.");            }            //是否预加载(具体为预加载 class / 类加载器 / 资源文件等)            if (!enableLazyPreload) {                bootTimingsTraceLog.traceBegin("ZygotePreload");                EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,                        SystemClock.uptimeMillis());                preload(bootTimingsTraceLog);                EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,                        SystemClock.uptimeMillis());                bootTimingsTraceLog.traceEnd(); // ZygotePreload            }            // Do an initial gc to clean up after startup            bootTimingsTraceLog.traceBegin("ostZygoteInitGC");            // 触发一次 gc (具体由 ZygoteHooks实行)            gcAndFinalize();            bootTimingsTraceLog.traceEnd(); // PostZygoteInitGC            bootTimingsTraceLog.traceEnd(); // ZygoteInit            Zygote.initNativeState(isPrimaryZygote);            ZygoteHooks.stopZygoteNoThreadCreation();            // ZygoteServer 做为 Socket 服务端,创建 socket 毗连            zygoteServer = new ZygoteServer(isPrimaryZygote);            // 创建 SystemSerrver 进程,通过 Zygote fork 出来,之后 SystemSerrver 负责创建 AMS 等紧张服务            if (startSystemServer) {                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();                    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.            // 轮询实行,先不关注这块            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();        }    }总结一下 Zygote 的启动过程:

  • 剖析 init.rc 创建 AppRunTime
  • 实行 AndroidRuntime.Start()
  • JNI 调用 ZygoteInit.main(),转到 Java 层了
  • 创建 Socket 服务端,准备相应客户端的哀求
  • 预加载
  • 通过 fork 的方式启动 SystemServer 进程
  • 开启轮询
干系链接


  • Framework 红橙Darren
  • SystemService 与 ServiceManager 的 区别
  • 一图摸清Android应用进程的启动
  • Linux 文件描述符是什么
  • Epoll 机制
  • Socket 底子知识
  • linux 内存底子
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 18:22, Processed in 0.199351 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表