3.Android 小米专家彻底解读SyetemServer ( 基于安卓12源码分析

23 篇文章 6 订阅
8 篇文章 0 订阅

SyetemServer进程是 Zygote 进程 fork 创建的!(通过C代码)

开始的时候只有uid,还没有pid

// fork 创建 system_server 进程,后面会具体分析
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
        null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);

入口:SystemServer里面的main函数!

 
public final class SystemServer {


/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}

SystemServiceManager,它会对系统的服务进行创建、启动和生命周期管理。启动系统的各种服务,在注释3中的startBootstrapServices函数中用SystemServiceManager启动了ActivityManagerService、PowerManagerService、PackageManagerService等服务。在注释4处的函数中则启动了BatteryService、UsageStatsService和WebViewUpdateService。注释5处的startOtherServices函数中则启动了CameraService、AlarmManagerService、VrManagerService等服务,这些服务的父类为SystemService。从注释3、4、5的函数可以看出,官方把系统服务分为了三种类型,分别是引导服务、核心服务和其他服务,其中其他服务为一些非紧要和一些不需要立即启动的服务。

// 启动引导服务 
startBootstrapServices();
// 启动核心服务 
startCoreServices();
// 启动其他服务
startOtherServices();

总结SyetemServer进程:

SyetemServer在启动时做了如下工作:
1.启动Binder线程池,这样就可以与其他进程进行通信。(通过java调用c启动的)
2.创建SystemServiceManager用于对系统的服务进行创建、启动和生命周期管理。
3.启动各种系统服务。

在这里,基本上都是java代码。

问题:ams,pms是什么时候启动的?

就是在systemServer进程启动的

看一看源码,分析下!!!

在启动根服务

private void startBootstrapServices() {
    // 阻塞等待与 installd 建立 socket 通道
    Installer installer = mSystemServiceManager.startService(Installer.class);

    // 启动服务 ActivityManagerService
    mActivityManagerService = mSystemServiceManager.startService(ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);

    // 启动服务 PackageManagerService
    mPackageManagerService = PackageManagerService.main(mSystemContext, installer, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    mPackageManager = mSystemContext.getPackageManager();

    // 设置 AMS , 把自己交给 ServiceManager. addService 去管理
    mActivityManagerService.setSystemProcess();

...
}

启动其他服务:watchdog,IMS,ServiceManager注册服务,准备AMS,PMS,WMS

private void startOtherServices() {
    // 启动闹钟服务
    mSystemServiceManager.startService(AlarmManagerService.class);
    // 初始化 Watchdog
    final Watchdog watchdog = Watchdog.getInstance();
    watchdog.init(context, mActivityManagerService);
    // 输入管理的 service
    inputManager = new InputManagerService(context);
    // WindowManagerService
    wm = WindowManagerService.main(...);
    // InputManagerService 和 WindowManagerService 都交给 ServiceManager 管理
    ServiceManager.addService(Context.WINDOW_SERVICE, wm);
    ServiceManager.addService(Context.INPUT_SERVICE, inputManager);
    // 启动input
    inputManager.start();
    // 显示启动界面
    ActivityManagerNative.getDefault().showBootMessage(...);
    // 状态栏管理
    statusBar = new StatusBarManagerService(context, wm);
    // JobSchedulerService
    mSystemServiceManager.startService(JobSchedulerService.class);
...
    // 准备好了 wms,  pms, ams 服务
    wm.systemReady();
    mPackageManagerService.systemReady();
    mActivityManagerService.systemReady();
}

里面有一个watchDog:

final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();

 
 
 
private Context mSystemContext;
private SystemServiceManager mSystemServiceManager;

创建了系统上下文!

private void createSystemContext() {
    ActivityThread activityThread = ActivityThread.systemMain();
    mSystemContext = activityThread.getSystemContext();
    mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

    final Context systemUiContext = activityThread.getSystemUiContext();
    systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}

启动systemUi

private static void startSystemUi(Context context, WindowManagerService windowManager) {
    PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
    Intent intent = new Intent();
    intent.setComponent(pm.getSystemUiServiceComponent());
    intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
    //Slog.d(TAG, "Starting service: " + intent);
    context.startServiceAsUser(intent, UserHandle.SYSTEM);
    windowManager.onSystemUiStarted();
}

AMS和PMS是SystemServer是里面的一个对象!

public final class SystemServer {

    private static final String TAG = "SystemServer";

    private Context mSystemContext;
    private SystemServiceManager mSystemServiceManager;

    // TODO: remove all of these references by improving dependency resolution and boot phases
    private PowerManagerService mPowerManagerService;
    private ActivityManagerService mActivityManagerService;
    private WindowManagerGlobalLock mWindowManagerGlobalLock;
    private WebViewUpdateService mWebViewUpdateService;
    private DisplayManagerService mDisplayManagerService;

AMS启动的时候干了什么事情?

源码:任务栈管理

public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

 
@VisibleForTesting
public ActivityManagerService(Injector injector, ServiceThread handlerThread) {
final boolean hasHandlerThread = handlerThread != null;
mInjector = injector;
mContext = mInjector.getContext();
mUiContext = null;
mAppErrors = null;
mPackageWatchdog = null;
mAppOpsService = mInjector.getAppOpsService(null /* file */, null /* handler */);
mBatteryStatsService = null;
mHandler = hasHandlerThread ? new MainHandler(handlerThread.getLooper()) : null;
mHandlerThread = handlerThread;
mConstants = hasHandlerThread
? new ActivityManagerConstants(mContext, this, mHandler) : null;
final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */);
mProcessList.init(this, activeUids);
mLowMemDetector = null;
mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);

mIntentFirewall = hasHandlerThread
? new IntentFirewall(new IntentFirewallInterface(), mHandler) : null;
mProcessCpuThread = null;
mProcessStats = null;
mProviderMap = null;
// For the usage of {@link ActiveServices#cleanUpServices} that may be invoked from
// {@link ActivityStackSupervisor#cleanUpRemovedTaskLocked}.
mServices = hasHandlerThread ? new ActiveServices(this) : null;
mSystemThread = null;
mUiHandler = injector.getUiHandler(null /* service */);
mUserController = hasHandlerThread ? new UserController(this) : null;
mPendingIntentController = hasHandlerThread
? new PendingIntentController(handlerThread.getLooper(), mUserController) : null;
mProcStartHandlerThread = null;
mProcStartHandler = null;
mHiddenApiBlacklist = null;
mFactoryTest = FACTORY_TEST_OFF;
}

问题:ServiceManager 是什么时候启动 的?

管理 SystemServer

ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());

mSystemServiceManager.startService(AlarmManagerService.class);

publishBinderService(Context.ALARM_SERVICE, mService);

/**
     * Publish the service so it is accessible to other services and apps.
     */
    protected final void publishBinderService(String name, IBinder service) {
        publishBinderService(name, service, false);
    }
 
 
    /**
     * Publish the service so it is accessible to other services and apps.
     */
    protected final void publishBinderService(String name, IBinder service,
            boolean allowIsolated) {
        ServiceManager.addService(name, service, allowIsolated);
    }

总结:不管是 ServiceManager.addService 还是 mSystemServiceManager.startService 都是调用的 ServiceManager.addService 方法。

RuntimeInit: 异常处理!

private static class LoggingHandler implements UncaughtExceptionHandler {
    public volatile boolean mTriggered;

    private LoggingHandler() {
        this.mTriggered = false;
    }

    public void uncaughtException(Thread t, Throwable e) {
        this.mTriggered = true;
        if (!RuntimeInit.mCrashing) {
            if (RuntimeInit.mApplicationObject == null && 1000 == Process.myUid()) {
                RuntimeInit.Clog_e("AndroidRuntime", "*** FATAL EXCEPTION IN SYSTEM PROCESS: " + t.getName(), e);
            } else {
                StringBuilder message = new StringBuilder();
                message.append("FATAL EXCEPTION: ").append(t.getName()).append("\n");
                String processName = ActivityThread.currentProcessName();
                if (processName != null) {
                    message.append("Process: ").append(processName).append(", ");
                }

                message.append("PID: ").append(Process.myPid());
                RuntimeInit.Clog_e("AndroidRuntime", message.toString(), e);
            }

        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值