【Android FrameWork (三)】- SystemServer

news2024/11/15 21:33:26

文章目录

  • 知识回顾
    • 启动第一个流程init
    • Zygote的流程
  • 前言
  • 源码分析
    • 1.system_server
    • 2.SystemServer.main
    • 3,startBootstrapServices
    • 4,startService
  • 拓展知识
    • LoadApk
    • context 对于Android context 大家是怎么理解的?
    • LocalServices.java: addServece方法中 ArrayMap和HashMap的区别?
    • AMS、PMS是谁启动的?他们都是独立的进程吗?
    • WatchDog 看门狗机制?
    • 简述system_server的启动
  • 总结


知识回顾

启动第一个流程init

1,挂载文件系统,创建文件目录 调用selinux_setup权限安全相关
2,初始化内存空间 初始化属性服务 创建Epoll 注册监听子进程重启异常操作等,对子进程进行线程守护
3,startPropertyServic 开启属性服务 进行监听
4,LoadBootScripts 加载init.rc文件 进行解析 调用do_class_start 文件开启service
5,Service::Start函数->fork子进程->并且执行app_process文件,开启了zygote

Zygote的流程

1,startVm函数注册jvm startReg函数注册jni环境唤起 Zygote.main
2,forkSystemServer
3,preload预加载class 系统资源
4,调用runSelectLoop函数循环等待客户端连接
5,有客户端的连接后调用processOneCommand()函数 fork进程,初始化进程,创建ProcessState初始化binder
6,根据请求的targetClass 执行Main函数

前言

Android系统在启动的时候有两个非常重要的进程,Zygote & system_server。SystemServer是系统用来启动service的入口,比如我们常用的 AMSWMSPMS等都是由它创建的。
SystemServer主要是创建SystemServiceManager,对系统服务进行创建、启动以及管理。


源码分析

1.system_server

Zygote启动之后会调用ZygoteInit.java的main函数,会执行forkSystemServer

 private static Runnable forkSystemServer(String abiList, String socketName,
            ZygoteServer zygoteServer) {
       
       ……………………

        /* Hardcoded command line to start the system server */
        //准备 开启system_server的参数
        String args[] = {
                "--setuid=1000",
                "--setgid=1000",
                "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,"
                        + "1024,1032,1065,3001,3002,3003,3006,3007,3009,3010",
                "--capabilities=" + capabilities + "," + capabilities,
                "--nice-name=system_server",
                "--runtime-args",
                "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
                "com.android.server.SystemServer",
        };
        ZygoteArguments parsedArgs = null;

        int pid;

        try {
            //把参数包装成ZygoteArguments
            parsedArgs = new ZygoteArguments(args);
            Zygote.applyDebuggerSystemProperty(parsedArgs);
            Zygote.applyInvokeWithSystemProperty(parsedArgs);

            boolean profileSystemServer = SystemProperties.getBoolean(
                    "dalvik.vm.profilesystemserver", false);
            if (profileSystemServer) {
                parsedArgs.mRuntimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
            }

            /* Request to fork the system server process */
//            fork出来system_server 还是调用到native层com_android_internal_os_Zygote_nativeForkSystemServer
            pid = Zygote.forkSystemServer(
                    parsedArgs.mUid, parsedArgs.mGid,
                    parsedArgs.mGids,
                    parsedArgs.mRuntimeFlags,
                    null,
                    parsedArgs.mPermittedCapabilities,
                    parsedArgs.mEffectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }

        /* For child process */
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
            //关闭掉ServerSocket
            zygoteServer.closeServerSocket();
//这里我们看到返回的是一个Runnable 就可以联想到Zygote中的MethodAndArgsCaller
            return handleSystemServerProcess(parsedArgs);
        }

        return null;
    }
//fork最终会调用到Native层
//com_android_internal_os_Zygote_nativeForkSystemServer
//。文件目录/frameworks/base/core/jni/com_android_internal_os_Zygote.cpp。

static jint com_android_internal_os_Zygote_nativeForkSystemServer(
        JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
        jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
        jlong effective_capabilities) {
  std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
                   fds_to_ignore(fds_to_close);

  fds_to_close.push_back(gUsapPoolSocketFD);

  if (gUsapPoolEventFD != -1) {
    fds_to_close.push_back(gUsapPoolEventFD);
    fds_to_ignore.push_back(gUsapPoolEventFD);
  }
  //调用forkCommon函数,这个之前在Zygote中有跟踪过,这里就不跟了。调用fork并返回pid_t
  pid_t pid = ForkCommon(env, true,
                         fds_to_close,
                         fds_to_ignore);
  if (pid == 0) {
      SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
                       permitted_capabilities, effective_capabilities,
                       MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
                       false, nullptr, nullptr);
  } else if (pid > 0) {
      ALOGI("System server process %d has been created", pid);
      gSystemServerPid = pid;
      int status;
      if (waitpid(pid, &status, WNOHANG) == pid) {//做一次安全检查
          ALOGE("System server process %d has died. Restarting Zygote!", pid);
          RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
      }

      if (UsePerAppMemcg()) {
          if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) {
              ALOGE("couldn't add process %d into system memcg group", pid);
          }
      }
  }
  return pid;
}


private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
    Os.umask(S_IRWXG | S_IRWXO);

    if (parsedArgs.mNiceName != null) {
        Process.setArgV0(parsedArgs.mNiceName);
    }

    final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
    if (systemServerClasspath != null) {
        if (performSystemServerDexOpt(systemServerClasspath)) {
            sCachedSystemServerClassLoader = null;
        }
        boolean profileSystemServer = SystemProperties.getBoolean(
                "dalvik.vm.profilesystemserver", false);
        if (profileSystemServer && (Build.IS_USERDEBUG || Build.IS_ENG)) {
            try {
                prepareSystemServerProfile(systemServerClasspath);
            } catch (Exception e) {
                Log.wtf(TAG, "Failed to set up system server profile", e);
            }
        }
    }

    if (parsedArgs.mInvokeWith != null) {//这里是Null
        String[] args = parsedArgs.mRemainingArgs;
        if (systemServerClasspath != null) {
            String[] amendedArgs = new String[args.length + 2];
            amendedArgs[0] = "-cp";
            amendedArgs[1] = systemServerClasspath;
            System.arraycopy(args, 0, amendedArgs, 2, args.length);
            args = amendedArgs;
        }

        WrapperInit.execApplication(parsedArgs.mInvokeWith,
                parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion,
                VMRuntime.getCurrentInstructionSet(), null, args);

        throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
    } else {
        createSystemServerClassLoader();//创建SystemServer的ClassLoader
        ClassLoader cl = sCachedSystemServerClassLoader;//将创建好的ClassLoader赋值给cl
        if (cl != null) {
            Thread.currentThread().setContextClassLoader(cl);
        }
        //调用ZygoteInit.zygoteInit 和Zygote一样 创建ProcessState 打开binder 并调用RuntimeInit.applicationInit 返回startClass的Main函数的caller也 也就是执行com.android.server.SystemServer的main函数
        return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
                parsedArgs.mRemainingArgs, cl);
    }

}



2.SystemServer.main

main函数转头就掉了run函数,run函数中 创建了Looper、加载了android_server函数库、创建了SystemServiceManager(对服务进行创建、启动和管理)并且添加到LocalService(一个ArrayMap)中、startBootstrapServices(开启引导服务)、startCoreServices(开启核心服务)、startOtherServices(开启其他服务)、Looper开启。

public static void main(String[] args) {
    //转头就钓了run函数
    new SystemServer().run();
}



private void run() {
    try {
        traceBeginAndSlog("InitBeforeStartServices");

        SystemProperties.set(SYSPROP_START_COUNT, String.valueOf(mStartCount));
        SystemProperties.set(SYSPROP_START_ELAPSED, String.valueOf(mRuntimeStartElapsedTime));
        SystemProperties.set(SYSPROP_START_UPTIME, String.valueOf(mRuntimeStartUptime));

        EventLog.writeEvent(EventLogTags.SYSTEM_SERVER_START,
                mStartCount, mRuntimeStartUptime, mRuntimeStartElapsedTime);

        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
        }

        String timezoneProperty = SystemProperties.get("persist.sys.timezone");
        if (timezoneProperty == null || timezoneProperty.isEmpty()) {
            Slog.w(TAG, "Timezone not set; setting to GMT.");
            SystemProperties.set("persist.sys.timezone", "GMT");
        }

        if (!SystemProperties.get("persist.sys.language").isEmpty()) {
            final String languageTag = Locale.getDefault().toLanguageTag();

            SystemProperties.set("persist.sys.locale", languageTag);
            SystemProperties.set("persist.sys.language", "");
            SystemProperties.set("persist.sys.country", "");
            SystemProperties.set("persist.sys.localevar", "");
        }

        Binder.setWarnOnBlocking(true);
        PackageItemInfo.forceSafeLabels();

        SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;

        SQLiteCompatibilityWalFlags.init(null);

        Slog.i(TAG, "Entered the Android system server!");
        int uptimeMillis = (int) SystemClock.elapsedRealtime();
        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
        if (!mRuntimeRestart) {
            MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
        }

        SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());

        VMRuntime.getRuntime().clearGrowthLimit();
        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
        Build.ensureFingerprintProperty();
        Environment.setUserRequired(true);
        BaseBundle.setShouldDefuse(true);
        Parcel.setStackTraceParceling(true);
        BinderInternal.disableBackgroundScheduling(true);
        BinderInternal.setMaxThreads(sMaxBinderThreads);
        android.os.Process.setThreadPriority(
                android.os.Process.THREAD_PRIORITY_FOREGROUND);
        android.os.Process.setCanSelfBackground(false);
        Looper.prepareMainLooper();//创建消息的Looper
        Looper.getMainLooper().setSlowLogThresholdMs(
                SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
        //加载函数库 libandroid_servers.so
        System.loadLibrary("android_servers");

        if (Build.IS_DEBUGGABLE) {
            initZygoteChildHeapProfiling();
        }

        performPendingShutdown();

        // Initialize the system context.
        createSystemContext();//创建系统Context

        // Create the system service manager. 创建ServiceManager
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setStartInfo(mRuntimeRestart,
                mRuntimeStartElapsedTime, mRuntimeStartUptime);
        //将SystemServiceManager添加到LocalServices中 LocalService 内部其实就是一个ArrayMap
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        // Prepare the thread pool for init tasks that can be parallelized
        SystemServerInitThreadPool.get();
    } finally {
        traceEnd();  // InitBeforeStartServices
    }

    // Start services. 开启服务
    try {
        traceBeginAndSlog("StartServices");
        startBootstrapServices();//开启引导服务
        startCoreServices();//开启核心服务
        startOtherServices();//开启其他服务
        SystemServerInitThreadPool.shutdown();
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    } finally {
        traceEnd();
    }

    StrictMode.initVmDefaults(null);

    if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
        int uptimeMillis = (int) SystemClock.elapsedRealtime();
        MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
        final int MAX_UPTIME_MILLIS = 60 * 1000;
        if (uptimeMillis > MAX_UPTIME_MILLIS) {
            Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
                    "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
        }
    }
    if (!VMRuntime.hasBootImageSpaces()) {
        Slog.wtf(TAG, "Runtime is not running with a boot image!");
    }

    // Loop forever.
    //loop启动
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}


3,startBootstrapServices

开启了看门狗(用于监控system_server,一旦出现问题会杀死SystemServer,SystemServer撕掉会告诉Zygote Zygote接收到之后会杀死自己 然后告诉init init又会重启Zygote并且激活对应的onRestart)以及相当多的服务,其中有我们熟悉的Installer、ActivityTaskManagerService、ActivityManagerService、PowerManagerService、PackageManagerService等等,基本上就是通过startService方法

private void startBootstrapServices() {
    traceBeginAndSlog("StartWatchdog");
    final Watchdog watchdog = Watchdog.getInstance();
    watchdog.start();//开启看门狗
    traceEnd();

    Slog.i(TAG, "Reading configuration...");
    final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
    traceBeginAndSlog(TAG_SYSTEM_CONFIG);
    SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
    traceEnd();

    traceBeginAndSlog("StartInstaller");
    //开启Installer服务
    Installer installer = mSystemServiceManager.startService(Installer.class);
    traceEnd();

    traceBeginAndSlog("DeviceIdentifiersPolicyService");
    //开启设备标识符访问策略服务
    mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
    traceEnd();

    traceBeginAndSlog("UriGrantsManagerService");
    mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);
    traceEnd();

    // Activity manager runs the show.
    traceBeginAndSlog("StartActivityManager");
    //启动ActivityTaskManagerService、mActivityManagerService服务并关联systemServiceManager以及installer
    ActivityTaskManagerService atm = mSystemServiceManager.startService(
            ActivityTaskManagerService.Lifecycle.class).getService();
    mActivityManagerService = ActivityManagerService.Lifecycle.startService(
            mSystemServiceManager, atm);
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);
    mWindowManagerGlobalLock = atm.getGlobalLock();
    traceEnd();

    // Power manager needs to be started early because other services need it.
    // Native daemons may be watching for it to be registered so it must be ready
    // to handle incoming binder calls immediately (including being able to verify
    // the permissions for those calls).
    traceBeginAndSlog("StartPowerManager");
    //开启PowerManagerService服务
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
    traceEnd();

    traceBeginAndSlog("StartThermalManager");
    mSystemServiceManager.startService(ThermalManagerService.class);
    traceEnd();

    // Now that the power manager has been started, let the activity manager
    // initialize power management features.
    traceBeginAndSlog("InitPowerManagement");
    mActivityManagerService.initPowerManagement();
    traceEnd();

    // Bring up recovery system in case a rescue party needs a reboot
    traceBeginAndSlog("StartRecoverySystemService");
    mSystemServiceManager.startService(RecoverySystemService.class);
    traceEnd();

    // Now that we have the bare essentials of the OS up and running, take
    // note that we just booted, which might send out a rescue party if
    // we're stuck in a runtime restart loop.
    RescueParty.noteBoot(mSystemContext);

    // Manages LEDs and display backlight so we need it to bring up the display.
    traceBeginAndSlog("StartLightsService");
    mSystemServiceManager.startService(LightsService.class);
    traceEnd();

    traceBeginAndSlog("StartSidekickService");
    // Package manager isn't started yet; need to use SysProp not hardware feature
    if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
        mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
    }
    traceEnd();

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

    // We need the default display before we can initialize the package manager.
    traceBeginAndSlog("WaitForDisplay");
    mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
    traceEnd();

    // Only run "core" apps if we're encrypting the device.
    String cryptState = VoldProperties.decrypt().orElse("");
    if (ENCRYPTING_STATE.equals(cryptState)) {
        Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
        mOnlyCore = true;
    } else if (ENCRYPTED_STATE.equals(cryptState)) {
        Slog.w(TAG, "Device encrypted - only parsing core apps");
        mOnlyCore = true;
    }

    // Start the package manager.
    if (!mRuntimeRestart) {
        MetricsLogger.histogram(null, "boot_package_manager_init_start",
                (int) SystemClock.elapsedRealtime());
    }
    traceBeginAndSlog("StartPackageManagerService");
    try {
        Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
        //创建PackageManagerService服务
        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    } finally {
        Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
    }
    mFirstBoot = mPackageManagerService.isFirstBoot();
    mPackageManager = mSystemContext.getPackageManager();
    traceEnd();
    if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
        MetricsLogger.histogram(null, "boot_package_manager_init_ready",
                (int) SystemClock.elapsedRealtime());
    }
    // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
    // A/B artifacts after boot, before anything else might touch/need them.
    // Note: this isn't needed during decryption (we don't have /data anyways).
    if (!mOnlyCore) {
        boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
                false);
        if (!disableOtaDexopt) {
            traceBeginAndSlog("StartOtaDexOptService");
            try {
                Watchdog.getInstance().pauseWatchingCurrentThread("moveab");
                OtaDexoptService.main(mSystemContext, mPackageManagerService);
            } catch (Throwable e) {
                reportWtf("starting OtaDexOptService", e);
            } finally {
                Watchdog.getInstance().resumeWatchingCurrentThread("moveab");
                traceEnd();
            }
        }
    }

    traceBeginAndSlog("StartUserManagerService");
    mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
    traceEnd();

    // Initialize attribute cache used to cache resources from packages.
    traceBeginAndSlog("InitAttributerCache");
    AttributeCache.init(mSystemContext);
    traceEnd();

    // Set up the Application instance for the system process and get started.
    traceBeginAndSlog("SetSystemProcess");
    mActivityManagerService.setSystemProcess();
    traceEnd();

    // Complete the watchdog setup with an ActivityManager instance and listen for reboots
    // Do this only after the ActivityManagerService is properly started as a system process
    traceBeginAndSlog("InitWatchdog");
    watchdog.init(mSystemContext, mActivityManagerService);
    traceEnd();

    // DisplayManagerService needs to setup android.display scheduling related policies
    // since setSystemProcess() would have overridden policies due to setProcessGroup
    mDisplayManagerService.setupSchedulerPolicies();

    // Manages Overlay packages
    traceBeginAndSlog("StartOverlayManagerService");
    mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));
    traceEnd();

    traceBeginAndSlog("StartSensorPrivacyService");
    mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));
    traceEnd();

    if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {
        // DisplayManager needs the overlay immediately.
        mActivityManagerService.updateSystemUiContext();
        LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();
    }

    // The sensor service needs access to package manager service, app ops
    // service, and permissions service, therefore we start it after them.
    // Start sensor service in a separate thread. Completion should be checked
    // before using it.
    mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
        TimingsTraceLog traceLog = new TimingsTraceLog(
                SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
        traceLog.traceBegin(START_SENSOR_SERVICE);
        startSensorService();
        traceLog.traceEnd();
    }, START_SENSOR_SERVICE);
}

4,startService

public <T extends SystemService> T startService(Class<T> serviceClass) {
    try {
        final String name = serviceClass.getName();
        Slog.i(TAG, "Starting " + name);
        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);

        if (!SystemService.class.isAssignableFrom(serviceClass)) {
            throw new RuntimeException("Failed to create " + name
                    + ": service must extend " + SystemService.class.getName());
        }
        final T service;
        try {
            Constructor<T> constructor = serviceClass.getConstructor(Context.class);
            service = constructor.newInstance(mContext);
        } catch (InstantiationException ex) {
            throw new RuntimeException("Failed to create service " + name
                    + ": service could not be instantiated", ex);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException("Failed to create service " + name
                    + ": service must have a public constructor with a Context argument", ex);
        } catch (NoSuchMethodException ex) {
            throw new RuntimeException("Failed to create service " + name
                    + ": service must have a public constructor with a Context argument", ex);
        } catch (InvocationTargetException ex) {
            throw new RuntimeException("Failed to create service " + name
                    + ": service constructor threw an exception", ex);
        }
        //通过反射创建传递过来的Service对象,调用startService
        startService(service);
        return service;
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
}

public void startService(@NonNull final SystemService service) {
        //将service添加到mServices中去
        mServices.add(service);
        long time = SystemClock.elapsedRealtime();
        try {
            //调用service的onStart函数启动对应的service
            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");
    }

拓展知识

LoadApk

LoadApk:理解为apk文件加载到内存的一个java对象 framework-res.apk

context 对于Android context 大家是怎么理解的?

LocalServices.java: addServece方法中 ArrayMap和HashMap的区别?

ArrayMap k,v k是int类型的包装,k是从小到大依次排列。时间复杂度可以是存的是 O(1). 取的过程就是log(n map.size). put和 get
HashMap <k(Object),v > 时间复杂度 put和 get O(1). K是一个复合类型,计算hash值 假如现在的k是String类型,那么就需要遍历当前字符串 计算当前“jijs”字符串的hash值存储到对应的位置上去 对应时间复杂度O(k) k复杂增长
ArrayList ?

AMS、PMS是谁启动的?他们都是独立的进程吗?

他们是由system_server启动,不是独立进程,他们都运行在system_server进程中。

WatchDog 看门狗机制?

原理:是一个单例模式,有一个handlerChecker集合,根据handler进行监控,监控所有的service 假如长时间未响应,AMS handler sendMessage(MQ)时间戳

简述system_server的启动

Zygote调用forkSystemServer来创建system_server进程,调用到Java层SystemServer.java.Main,创建SystemServer的ActivityThread 创建framewok-res.apk的Application调用onCreate,调用startBootstrapServices、startCoreServices、startOtherServices创建各种各样的Service(AMS、PMS等),并开启开门狗检测服务和线程,如果出现问题就会杀死system_server,system_server死亡之后会通知Zygote,
Zygote会杀死自己 通知init, init有线程守护,会重启Zygote 并执行对应的onRestart服务。

总结

1.system_server是在Zygote启动的时候fork出来的子进程,调用的是ZygoteInit.forkSystemServer,最终返回MethodAndArgsCaller包装的是com.android.server.SystemServer.Main。

2.SystemServer.Main函数直接调用了run函数,在run函数中调用了createSystemContext通过ActivityThread.systemMain创建了ActivityThread,设置了mSystemContext并且调用ActivityThread.attach 通过反射创建Application 执行onCreate函数.这里创建的app是framewok-res.apk,是给系统使用的 比如系统的对话框。将mSystemServiceManager添加到LocalService的mService(ArrayMap)中去接着调用startBootstrapServices、startCoreServices、startOtherServices开启了非常多的服务Installer、ATMS、AMS、PMS等。把他们添加到SystemServiceManager的mServices(ArrayList)中去。
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/458773.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Matlab 绘制双纵轴三纵轴图

三纵轴图 三坐标的图在前文中有所介绍&#xff1b;这次主要讲绘制双轴。 matlab 绘制三坐标&#xff08;轴&#xff09;图 绘制双纵轴图: yyaxis 简单用法 在MATLAB中&#xff0c;yyaxis可以用于绘制具有两个不同y轴的图形。以下是yyaxis的简单用法&#xff1a; 1.首先&am…

UG NX二次开发(C#)-UIStyler-找不到指定的Dlx文件的错误解决方法

1、项目场景: 在UG NX二次开发过程中,我们为了更好的操作,采用UI Styler设计了软件界面,然后按照UI Styler的编程流程成功的生成了dll,但是在采用Ctrl+U或者用“文件“->“执行”->"NX Open"执行dll时,遇到如下图所示的错误页面,提示内容为:找不到指定…

成就更强大的自己

每一次低谷&#xff0c;都会酝酿向上的力量。 每一次痛苦过后&#xff0c;都会洗涤掉心理深处的灰尘。 人生的路上&#xff0c;坎坷前行&#xff0c;只有保持积极向上的态度&#xff0c;才能把坎坷化为坦途。 走过一段路后&#xff0c;才发现&#xff0c;当内心强大、修养、爱…

Android之 颜色选择器

一&#xff0c;简介 1.1 计算机的颜色通常有两种表示方式&#xff1a; 光源模式RGB(Red红, Green绿, Blue蓝)&#xff0c;数值0-255 印刷模式CMYK(Cyan青, Magenta品红, Yellow黄, Black黑)&#xff0c;数值1-100 任何颜色都是由RGB或CMYK混合出来的&#xff0c;再加上透明度…

2023年产业基金研究报告

第一章 行业概况 1.1 概述 产业基金&#xff0c;又称为产业投资基金&#xff0c;是一种由政府、企业、金融机构等出资设立的&#xff0c;专门用于支持和促进特定产业发展的投资基金。产业基金通常以股权投资和长期投资为主&#xff0c;旨在推动产业结构升级、促进科技创新、提…

算法刷题|139.单词拆分、多重背包

单词拆分 题目&#xff1a;给你一个字符串 s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s 。 注意&#xff1a;不要求字典中出现的单词全部都使用&#xff0c;并且字典中的单词可以重复使用。 思路&#xff1a;字符串s就是我们的背包…

【移动端网页布局】流式布局案例 ① ( 视口标签设置 | CSS 样式文件设置 | 布局宽度设置 | 设置最大宽度 | 设置最小宽度 )

文章目录 一、视口标签设置二、CSS 样式文件设置三、布局宽度设置1、设置布局宽度2、设置布局最大宽度3、设置布局最小宽度4、查看网页最大最小宽度5、布局宽度设置 四、代码示例1、主界面标签2、CSS 布局设置 一、视口标签设置 参考 【移动端网页布局】移动端网页布局基础概念…

打造卓越游戏 | 2023 Google 游戏开发者峰会

一款游戏从初始构想的开发到辉煌赛季的策划&#xff0c;开发者们每时每刻都在倾注心血潜心钻研&#xff0c;Google 也致力于在整个开发和发布生命周期中为您提供帮助。我们很高兴能在今年如约而至的 Google 游戏开发者峰会中与您分享诸多更新&#xff0c;展示我们为助力您打造精…

JavaScript常用方法整理

文章目录 前言1.栈方法&#xff1a;push()、pop()2.队列方法&#xff1a;unshift()、shift()3.indexof()、lastIndexOf()、includes()4.操作方法&#xff1a;concat()、slice()、splice()5.Array.isArray()6.排序方法:sort()、reverse()7.转换方法&#xff1a;toString()、join…

input 元素 change 事件失效,失去焦点的时候才执行?什么原因导致?如何正确使用?

具体问题如标题所示&#xff0c;不再过多水字数&#xff0c;请看下面的代码&#xff1a; <input :class"[custom-form-item-input, (isFocusUserName && !userName) ? custom-form-item-input-err-active : ]"autoCompletenew-password type"text&…

带着疑问学C语言-C语言常用变量

目录 目录 一、声明变量和定义变量的区别是什么&#xff1f; 二、什么常量&#xff0c;如何区分常量和变量&#xff1f; 三、各数据类型所占的内存是多少&#xff1f; 四、字符与字符串的差别有哪些&#xff1f; 五、为什么会发生数据溢出&#xff0c;如何避免数据溢出&am…

springboot整合juit和springboot整合mybatis和springboot整合ssm

springboot整合juit 先看一眼包路径&#xff0c;发现main程序的路径和测试类的路径是一样的 启用新注解&#xff1a;SpringBootTest代替了之前sm整合juit时的 RunWith(SpringJUnit4ClassRunner.class) //spring配置类 ContextConfiguration(classes config.class)新的如此…

数字北京城,航行在联通2000M的“大运河”

前故宫博物院院长单霁翔&#xff0c;在《大运河漂来紫禁城》一书中提到过&#xff0c;紫禁城里的石材、木材&#xff0c;甚至每一块砖&#xff0c;都是通过大运河&#xff0c;跋山涉水来到北京的。某种程度上说&#xff0c;北京城的繁荣与这条纵跨南北的“中华大动脉”密不可分…

OpenGL入门教程之 变换

引言 这是一个闪耀的时刻&#xff0c;因为我们即将能生产出令人惊叹的3D效果&#xff01; 变换 向量和矩阵变换包括太多内容&#xff0c;但由于学过线性代数和GAMES101&#xff0c;因此不在此做过多阐述。仅阐述包括代码的GLM内容。 GLM的使用 &#xff08;1&#xff09;GLM…

拓扑排序例题 P4017 最大食物链计数

拓扑排序例题 P4017 最大食物链计数 题目链接&#xff1a;P4017 最大食物链计数 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 最大食物链计数 题目背景 你知道食物链吗&#xff1f;Delia 生物考试的时候&#xff0c;数食物链条数的题目全都错了&#xff0c;因为她总是重…

陆奇博士4月23日深圳奇绩创坛分享会PPT及核心观点:新范式、新时代、新机遇(附PPT下载链接)...

省时查报告-专业、及时、全面的行研报告库 省时查方案-专业、及时、全面的营销策划方案库 【免费下载】2023年3月份热门报告合集 【限时免费】ChatGPT4体验&#xff0c;无需翻墙直接用 ChatGPT调研报告&#xff08;仅供内部参考&#xff09; ChatGPT的发展历程、原理、技术架构…

记录-使用双token实现无感刷新,前后端详细代码

这里给大家分享我在网上总结出来的一些知识&#xff0c;希望对大家有所帮助 前言 近期写的一个项目使用双token实现无感刷新。最后做了一些总结&#xff0c;本文详细介绍了实现流程&#xff0c;前后端详细代码。前端使用了Vue3Vite&#xff0c;主要是axios封装&#xff0c;服务…

Unity之OpenXR+XR Interaction Toolkit接入Pico VR一体机

一.前言 Pico VR 一体机是目前国内比较流行的VR设备之一&#xff0c;PICO成立于2015年3月&#xff0c;于2021年9月并入字节跳动。最新推出的Pico4一体机售价只有2400左右&#xff0c;这让很多家庭都入手了Pico设备&#xff0c;VR一体机的功能包括&#xff1a;VR全景视频&#…

学成在线笔记+踩坑(8)——课程预览、提交审核,Freemarker模板引擎

导航&#xff1a; 【黑马Java笔记踩坑汇总】JavaSEJavaWebSSMSpringBoot瑞吉外卖SpringCloud黑马旅游谷粒商城学成在线牛客面试题_java黑马笔记 目录 1 模块需求分析 1.1 模块介绍 1.2 业务流程 1.2.1 课程预览 1.2.2 课程审核 1.2.3 课程发布 2 课程预览 2.1 需求分析…

深度学习 - 43.SeNET、Bilinear Interaction 实现特征交叉 By Keras

目录 一.引言 二.SENET Layer 1.简介 2.Keras 实现 2.1 Init Function 2.2 Build Function 2.3 Call Function 2.4 Test Main Function 2.5 完整代码 三.BiLinear Intercation Layer 1.简介 2.Keras 实现 2.1 Init Function 2.2 Build Function 2.3 Call Functi…