SystemServer源码分析

从SystemServer的main函数入手

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

这里创建了一个SystemServer并调用了它的run()函数,进入run()函数,这个方法内部比较多,分段分析:

时间处理

// If a device‘s clock is before 1970 (before 0), a lot of
// APIs crash dealing with negative numbers, notably
// java.io.File#setLastModified, so instead we fake it and
// hope that time from cell towers or NTP fixes it shortly.
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
    Slog.w(TAG, "System clock is before 1970; setting to 1970.");
    SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}

一些API使用负数的时间时会导致异常,因此我们先在这里进行处理

性能统计

// Enable the sampling profiler.
if (SamplingProfilerIntegration.isEnabled()) {
    SamplingProfilerIntegration.start();
    mProfilerSnapshotTimer = new Timer();
    mProfilerSnapshotTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            SamplingProfilerIntegration.writeSnapshot("system_server", null);
        }
    }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
}

使用一个Timer每个小时执行一次writeSnapshot方法,进入到该方法中:

public static void writeSnapshot(final String processName, final PackageInfo packageInfo) {
    if (!enabled) {
        return;
    }
    if (samplingProfiler == null) {
        Log.e(TAG, "SamplingProfilerIntegration is not started");
        return;
    }

    if (pending.compareAndSet(false, true)) {
        snapshotWriter.execute(new Runnable() {
            public void run() {
                try {
                    writeSnapshotFile(processName, packageInfo);
                } finally {
                    pending.set(false);
                }
            }
        });
    }
}

snapshotWriter是什么?通过SamplingProfilerIntegration中的静态代码块可以知道,snapshotWriter是一个的线程池,每次只有一个线程执行队列中的任务

snapshotWriter = Executors.newSingleThreadExecutor(new ThreadFactory() {
    public Thread newThread(Runnable r) {
        return new Thread(r, TAG);
    }
});

继续进入到writeSnapshotFile方法

private static void writeSnapshotFile(String processName, PackageInfo packageInfo) {
    if (!enabled) {
        return;
    }
    samplingProfiler.stop();

    /*
     * We use the global start time combined with the process name
     * as a unique ID. We can‘t use a counter because processes
     * restart. This could result in some overlap if we capture
     * two snapshots in rapid succession.
     */
    String name = processName.replaceAll(":", ".");
    String path = SNAPSHOT_DIR + "/" + name + "-" + startMillis + ".snapshot";
    long start = System.currentTimeMillis();
    OutputStream outputStream = null;
    try {
        outputStream = new BufferedOutputStream(new FileOutputStream(path));
        PrintStream out = new PrintStream(outputStream);
        generateSnapshotHeader(name, packageInfo, out);
        if (out.checkError()) {
            throw new IOException();
        }
        BinaryHprofWriter.write(samplingProfiler.getHprofData(), outputStream);
    } catch (IOException e) {
        Log.e(TAG, "Error writing snapshot to " + path, e);
        return;
    } finally {
        IoUtils.closeQuietly(outputStream);
    }
    // set file readable to the world so that SamplingProfilerService
    // can put it to dropbox
    new File(path).setReadable(true, false);

    long elapsed = System.currentTimeMillis() - start;
    Log.i(TAG, "Wrote snapshot " + path + " in " + elapsed + "ms.");
    samplingProfiler.start(samplingProfilerMilliseconds);
}

主要就是将性能统计信息以文件保存在SNAPSHOT_DIR目录中,每个文件的命名规则为:name + “-” + startMillis + “.snapshot”

初始化android_services

// Initialize native services.
System.loadLibrary("android_servers");
/**
 * Called to initialize native system services.
 */
nativeInit();

nativeInit方法为navite方法,为libandroid_servers.so里边的方法

初始化主线程的Looper

/**
 * Initialize the current thread as a looper, marking it as an
 * application‘s main looper. The main looper for your application
 * is created by the Android environment, so you should never need
 * to call this function yourself.  See also: {@link #prepare()}
 */
Looper.prepareMainLooper();

初始化system context

// Initialize the system context.
createSystemContext();

private void createSystemContext() {
    ActivityThread activityThread = ActivityThread.systemMain();
    mSystemContext = activityThread.getSystemContext();
    mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
}

首先,看看ActivityThread是什么?

/**
 * This manages the execution of the main thread in an
 * application process, scheduling and executing activities,
 * broadcasts, and other operations on it as the activity
 * manager requests.
 *
 * {@hide}
 */

大概原意:管理着某个应用程序进程的主线程中的执行,包括:调度和执行activitys、broadcast和其他由ActivityManager请求的操作

这里主要做了三步操作:

  1. 调用systemMain方法,创建一个ActivityThread
public static ActivityThread systemMain() {
    // The system process on low-memory devices do not get to use hardware
    // accelerated drawing, since this can add too much overhead to the
    // process.
    if (!ActivityManager.isHighEndGfx()) {
        HardwareRenderer.disable(true);
    } else {
        HardwareRenderer.enableForegroundTrimming();
    }
    ActivityThread thread = new ActivityThread();
    thread.attach(true);
    return thread;
}
  • 通过ActivityManager.isHighEndGfx()判断是否运行在大内存的设备中:假如是,则开启硬件加速;否则关闭
  • 创建一个ActivityThread,并调用其attath方法
private void attach(boolean system) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {
        ......
        ......
        // 省略部分代码
    } else {
        android.ddm.DdmHandleAppName.setAppName("system_process",
                UserHandle.myUserId());
        try {
            mInstrumentation = new Instrumentation();
            ContextImpl context = ContextImpl.createAppContext(
                    this, getSystemContext().mPackageInfo);
            mInitialApplication = context.mPackageInfo.makeApplication(true, null);
            mInitialApplication.onCreate();
        } catch (Exception e) {
            throw new RuntimeException(
                    "Unable to instantiate Application():" + e.toString(), e);
        }
    }

    // add dropbox logging to libcore
    DropBox.setReporter(new DropBoxReporter());

    ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            synchronized (mResourcesManager) {
                // We need to apply this change to the resources
                // immediately, because upon returning the view
                // hierarchy will be informed about it.
                if (mResourcesManager.applyConfigurationToResourcesLocked(newConfig, null)) {
                    // This actually changed the resources!  Tell
                    // everyone about it.
                    if (mPendingConfiguration == null ||
                            mPendingConfiguration.isOtherSeqNewer(newConfig)) {
                        mPendingConfiguration = newConfig;

                        sendMessage(H.CONFIGURATION_CHANGED, newConfig);
                    }
                }
            }
        }
        @Override
        public void onLowMemory() {
        }
        @Override
        public void onTrimMemory(int level) {
        }
    });
}
  • Instrumentation:创建该类的实例,该类用于监控该应用与系统之间的交互

    • 调用ContextImpl.createAppContext()创建一个ContextImpl
  • 调用context.mPackageInfo.makeApplication(true, null)创建该应用的Application对象,并调用该Application的onCreate()方法:这里启动了一个包名为android的系统应用程序
  • 设置监听配置更新的回调
    1. 回到createSystemContext()方法,创建了ActivityThread之后,获取ContextImpl的引用,并保存在本地
mSystemContext = activityThread.getSystemContext();

public ContextImpl getSystemContext() {
    synchronized (this) {
        if (mSystemContext == null) {
            mSystemContext = ContextImpl.createSystemContext(this);
        }
        return mSystemContext;
    }
}
  1. 调用ContextImpl的setTheme()方法设置默认主题

回到SystemServer的run()方法,接着往下看

// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
  • 创建一个SystemServiceManager对象
  • 将该对象添加到LocalServices中

    LocalServices类似与ServiceManger,但在这里注册的services不属于Binder对象,而且只能在该进程中有效

启动一系列的服务

// Start services.
try {
    startBootstrapServices();
    startCoreServices();
    startOtherServices();
} catch (Throwable ex) {
    Slog.e("System", "******************************************");
    Slog.e("System", "************ Failure starting system services", ex);
    throw ex;
}

这里分开三个部分启动services

1 startBootstrapServices()

// 先看下官方对这个方法的说明
/**
 * Starts the small tangle of critical services that are needed to get
 * the system off the ground.  These services have complex mutual dependencies
 * which is why we initialize them all in one place here.  Unless your service
 * is also entwined in these dependencies, it should be initialized in one of
 * the other functions.
 */

大概原意是:在这个方法里边启动一些琐碎但重要的services,这些服务支持着system正常的运行。它们由于相互依赖紧密,因此需要在同一个地方进行初始化。除非你的服务也跟它们有着紧密依赖,否则就应该在其他的方法进行初始化
- Installer:

// Wait for installd to finish starting up so that it has a chance to
// create critical directories such as /data/user with the appropriate
// permissions.  We need this to complete before we initialize other services.
mInstaller = mSystemServiceManager.startService(Installer.class);

这里通过mSystemServiceManager.startService()方法创建了一个Installer,并执行它的onStart()方法

private final InstallerConnection mInstaller;

@Override
public void onStart() {
    Slog.i(TAG, "Waiting for installd to be ready.");
    ping();
}

public boolean ping() {
    if (mInstaller.execute("ping") < 0) {
        return false;
    } else {
        return true;
    }
}

public int execute(String cmd) {
    String res = transact(cmd);
    try {
        return Integer.parseInt(res);
    } catch (NumberFormatException ex) {
        return -1;
    }
}

public synchronized String transact(String cmd) {
    if (!connect()) {
        Slog.e(TAG, "connection failed");
        return "-1";
    }

    if (!writeCommand(cmd)) {
        /*
         * If installd died and restarted in the background (unlikely but
         * possible) we‘ll fail on the next write (this one). Try to
         * reconnect and write the command one more time before giving up.
         */
        Slog.e(TAG, "write command failed? reconnect!");
        if (!connect() || !writeCommand(cmd)) {
            return "-1";
        }
    }
    if (LOCAL_DEBUG) {
        Slog.i(TAG, "send: ‘" + cmd + "‘");
    }

    final int replyLength = readReply();
    if (replyLength > 0) {
        String s = new String(buf, 0, replyLength);
        if (LOCAL_DEBUG) {
            Slog.i(TAG, "recv: ‘" + s + "‘");
        }
        return s;
    } else {
        if (LOCAL_DEBUG) {
            Slog.i(TAG, "fail");
        }
        return "-1";
    }
}

上边的代码作用:InstallerConnection与installed通过LocalSocket链接,并通过‘ping’命令检查是否链接成功。***主要就是启动installed服务**

  • ActivityManagerService
// Activity manager runs the show.
mActivityManagerService = mSystemServiceManager.startService(
        ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);

private void start() {
    // 清除所有的进程组
    Process.removeAllProcessGroups();
    // 启动用于统计CPU占用的Thread
    mProcessCpuThread.start();
    // 启动BatteryStatsService
    mBatteryStatsService.publish(mContext);
    // 启动AppOpsService
    mAppOpsService.publish(mContext);
    Slog.d("AppOps", "AppOpsService published");
    // 将ActivityManagerService注册到LocalServices中
    LocalServices.addService(ActivityManagerInternal.class, new LocalService());
}

上边的代码作用:启动一个ActivityManagerService,并将其注册到LocalServices中;并调用了ActivityManagerService的onStart()方法,并启动了其他一些服务

- PowerManagerService

// 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).
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

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

其他服务可能需要使用到PowerManagerService,因此需要尽早的启动该服务。等它启动后,使用ActivityManagerService初始化电源管理功能

- DisplayManagerService

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

显示管理器需要在包管理器启动前提供显示度量

  • PackageManagerService
// Start the package manager.
Slog.i(TAG, "Package Manager");
mPackageManagerService = PackageManagerService.main(mSystemContext, mInstaller,
        mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();

启动PackageManagerService,在后边的文章再详细说明

  • UserManagerService
Slog.i(TAG, "User Service");
ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());

启动UserManagerService

  • AttributeCache
// Initialize attribute cache used to cache resources from packages.AttributeCache.init(mSystemContext);

初始化AttributeCache用于缓存每个应用包的资源

  • setSystemProcess
// Set up the Application instance for the system process and get started.
mActivityManagerService.setSystemProcess();

public void setSystemProcess() {
    try {
        ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
        ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
        ServiceManager.addService("meminfo", new MemBinder(this));
        ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
        ServiceManager.addService("dbinfo", new DbBinder(this));
        if (MONITOR_CPU_USAGE) {
            ServiceManager.addService("cpuinfo", new CpuBinder(this));
        }
        ServiceManager.addService("permission", new PermissionController(this));

        ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                "android", STOCK_PM_FLAGS);
        mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

        synchronized (this) {
            ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
            app.persistent = true;
            app.pid = MY_PID;
            app.maxAdj = ProcessList.SYSTEM_ADJ;
            app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
            mProcessNames.put(app.processName, app.uid, app);
            synchronized (mPidsSelfLocked) {
                mPidsSelfLocked.put(app.pid, app);
            }
            updateLruProcessLocked(app, false, null);
            updateOomAdjLocked();
        }
    } catch (PackageManager.NameNotFoundException e) {
        throw new RuntimeException(
                "Unable to find android system package", e);
    }
}

2 startCoreServices()

/**
 * Starts some essential services that are not tangled up in the bootstrap process.
 */
private void startCoreServices() {
    // Manages LEDs and display backlight.
    mSystemServiceManager.startService(LightsService.class);

    // Tracks the battery level.  Requires LightService.
    mSystemServiceManager.startService(BatteryService.class);

    // Tracks application usage stats.
    mSystemServiceManager.startService(UsageStatsService.class);
    mActivityManagerService.setUsageStatsManager(
            LocalServices.getService(UsageStatsManagerInternal.class));

    // Tracks whether the updatable WebView is in a ready state and watches for update installs.
    mSystemServiceManager.startService(WebViewUpdateService.class);
}
  • LightsService:管理LED灯和背光灯的服务
  • BatteryService:电源管理服务
  • UsageStatsService:应用使用状跟踪服务
  • WebView更新服务

3 startOtherServices()

private void startOtherServices() {

    // 1. 根据配置启动一些相应的服务
    // 2. Bring up services needed for UI.启动一些跟UI相关的services
    // 3. 重点
    mActivityManagerService.systemReady(new Runnable() {
            @Override
            public void run() {
                Slog.i(TAG, "Making services ready");
                mSystemServiceManager.startBootPhase(
                        SystemService.PHASE_ACTIVITY_MANAGER_READY);

                try {
                    mActivityManagerService.startObservingNativeCrashes();
                } catch (Throwable e) {
                    reportWtf("observing native crashes", e);
                }

                Slog.i(TAG, "WebViewFactory preparation");
                WebViewFactory.prepareWebViewInSystemServer();

                try {
                    startSystemUi(context);
                } catch (Throwable e) {
                    reportWtf("starting System UI", e);
                }
                try {
                    if (mountServiceF != null) mountServiceF.systemReady();
                } catch (Throwable e) {
                    reportWtf("making Mount Service ready", e);
                }
                try {
                    if (networkScoreF != null) networkScoreF.systemReady();
                } catch (Throwable e) {
                    reportWtf("making Network Score Service ready", e);
                }
                try {
                    if (networkManagementF != null) networkManagementF.systemReady();
                } catch (Throwable e) {
                    reportWtf("making Network Managment Service ready", e);
                }
                try {
                    if (networkStatsF != null) networkStatsF.systemReady();
                } catch (Throwable e) {
                    reportWtf("making Network Stats Service ready", e);
                }
                try {
                    if (networkPolicyF != null) networkPolicyF.systemReady();
                } catch (Throwable e) {
                    reportWtf("making Network Policy Service ready", e);
                }
                try {
                    if (connectivityF != null) connectivityF.systemReady();
                } catch (Throwable e) {
                    reportWtf("making Connectivity Service ready", e);
                }
                try {
                    if (audioServiceF != null) audioServiceF.systemReady();
                } catch (Throwable e) {
                    reportWtf("Notifying AudioService running", e);
                }
                Watchdog.getInstance().start();

                // It is now okay to let the various system services start their
                // third party code...
                mSystemServiceManager.startBootPhase(
                        SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);

                try {
                    if (wallpaperF != null) wallpaperF.systemRunning();
                } catch (Throwable e) {
                    reportWtf("Notifying WallpaperService running", e);
                }
                try {
                    if (immF != null) immF.systemRunning(statusBarF);
                } catch (Throwable e) {
                    reportWtf("Notifying InputMethodService running", e);
                }
                try {
                    if (locationF != null) locationF.systemRunning();
                } catch (Throwable e) {
                    reportWtf("Notifying Location Service running", e);
                }
                try {
                    if (countryDetectorF != null) countryDetectorF.systemRunning();
                } catch (Throwable e) {
                    reportWtf("Notifying CountryDetectorService running", e);
                }
                try {
                    if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
                } catch (Throwable e) {
                    reportWtf("Notifying NetworkTimeService running", e);
                }
                try {
                    if (commonTimeMgmtServiceF != null) {
                        commonTimeMgmtServiceF.systemRunning();
                    }
                } catch (Throwable e) {
                    reportWtf("Notifying CommonTimeManagementService running", e);
                }
                try {
                    if (textServiceManagerServiceF != null)
                        textServiceManagerServiceF.systemRunning();
                } catch (Throwable e) {
                    reportWtf("Notifying TextServicesManagerService running", e);
                }
                try {
                    if (atlasF != null) atlasF.systemRunning();
                } catch (Throwable e) {
                    reportWtf("Notifying AssetAtlasService running", e);
                }
                try {
                    // TODO(BT) Pass parameter to input manager
                    if (inputManagerF != null) inputManagerF.systemRunning();
                } catch (Throwable e) {
                    reportWtf("Notifying InputManagerService running", e);
                }
                try {
                    if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
                } catch (Throwable e) {
                    reportWtf("Notifying TelephonyRegistry running", e);
                }
                try {
                    if (mediaRouterF != null) mediaRouterF.systemRunning();
                } catch (Throwable e) {
                    reportWtf("Notifying MediaRouterService running", e);
                }

                try {
                    if (mmsServiceF != null) mmsServiceF.systemRunning();
                } catch (Throwable e) {
                    reportWtf("Notifying MmsService running", e);
                }
            }
        });
    }

}

我们进入ActivityManagerService的systemReady()方法:

由于mSystemReady默认为false,因此Runnale的run()方法没有执行,而是执行了systemReady下边的代码:

......
......
// 省略部分代码
mBooting = true;
startHomeActivityLocked(mCurrentUserId);

在这里启动了第一个Activity,即Home

boolean startHomeActivityLocked(int userId) {
    if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
            && mTopAction == null) {
        // We are running in factory test mode, but unable to find
        // the factory test app, so just sit around displaying the
        // error message and don‘t try to start anything.
        return false;
    }
    Intent intent = getHomeIntent();
    ActivityInfo aInfo =
        resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
    if (aInfo != null) {
        intent.setComponent(new ComponentName(
                aInfo.applicationInfo.packageName, aInfo.name));
        // Don‘t do this if the home app is currently being
        // instrumented.
        aInfo = new ActivityInfo(aInfo);
        aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
        ProcessRecord app = getProcessRecordLocked(aInfo.processName,
                aInfo.applicationInfo.uid, true);
        if (app == null || app.instrumentationClass == null) {
            intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
            mStackSupervisor.startHomeActivity(intent, aInfo);
        }
    }

    return true;
}

Intent getHomeIntent() {
    Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
    intent.setComponent(mTopComponent);
    if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
        intent.addCategory(Intent.CATEGORY_HOME);
    }
    return intent;
}

public static final String CATEGORY_HOME = "android.intent.category.HOME";

可以看到我们在AndroidManifest中配置要启动的Activity需要添加该”android.intent.category.HOME”category的原因,在这里可以体现

总结

至此,整个SystemServer的流程就分析完了,SystemServer内部主要就是启动一系列必要的系统services

时间: 2024-08-02 13:27:20

SystemServer源码分析的相关文章

Android的软件包管理服务PackageManagerService源码分析

Android系统下的apk程序都是通过名为PackageManagerService的包管理服务来管理的.PacketManagerService是安卓系统的一个重要服务,由SystemServer启动,主要实现apk程序包的解析,安装,更新,移动,卸载等服务.不管是系统apk(/system/app),还是我们手工安装上去的,系统所有的apk都是由其管理的. 以android 4.0.4的源码为例,android4.0.4/frameworks/base/services/java/com/

Android 4.2 Wifi Display 之 Settings 源码分析(一)

一.简单背景 简单背景:随着无线互联的深入,不管是蓝牙.WIFI或者各种基于此的规范不管是UPNP还是DLNA都随着用户的需求得到了很大的发展,google 自从android 4.0引入wifi direct后,又在11月份公布的android 4.2中引入了Miracast无线显示共享,其协议在此可以下载.具体的协议部分内容比较多,本人由于水平有限,就不在这里罗列协议的内容了,只附上一份架构图供大家对其有个大致的印象. 英文缩写对应如下: HIDC: Human Interface Devi

Android 源码分析工具

标 题: [原创]Android源码分析工具及方法作 者: MindMac时 间: 2014-01-02,09:32:35链 接: http://bbs.pediy.com/showthread.php?t=183278 在对 Android 源码进行分析时,如果有得力的工具辅助,会达到事半功倍的效果.本文介绍了一些在分析 Android 源码时使用的一些工具和方法,希望能够帮助到有需要的同学. Eclipse 在 Android 应用程序开发过程中,一般会使用 Eclipse,当然 Googl

插件开发之360 DroidPlugin源码分析(五)Service预注册占坑

请尊重分享成果,转载请注明出处: http://blog.csdn.net/hejjunlin/article/details/52264977 在了解系统的activity,service,broadcastReceiver的启动过程后,今天将分析下360 DroidPlugin是如何预注册占坑的?本篇文章主要分析Service预注册占坑,Service占了坑后又是什么时候开始瞒天过海欺骗AMS的?先看下Agenda: AndroidMainfest.xml中概览 Service中关键方法被h

Android源码分析--system_server进程分析

在上一篇博文中我们进行了有关Zygote进程的分析,我们知道Zygote进程创建了一个重要的进程–system_server进程后就进入了无限循环中,之后Android系统中的重要任务就交给了system_server进程,作为zygote的嫡长子进程,system_server进程的意义非凡,今天我们来分析一下system_server进程. 创建system_server进程 在ZygoteInit中main方法中,通过调用startSystemServer方法开启了system_serve

TeamTalk源码分析之login_server

login_server是TeamTalk的登录服务器,负责分配一个负载较小的MsgServer给客户端使用,按照新版TeamTalk完整部署教程来配置的话,login_server的服务端口就是8080,客户端登录服务器地址配置如下(这里是win版本客户端): 1.login_server启动流程 login_server的启动是从login_server.cpp中的main函数开始的,login_server.cpp所在工程路径为server\src\login_server.下表是logi

Android触摸屏事件派发机制详解与源码分析二(ViewGroup篇)

1 背景 还记得前一篇<Android触摸屏事件派发机制详解与源码分析一(View篇)>中关于透过源码继续进阶实例验证模块中存在的点击Button却触发了LinearLayout的事件疑惑吗?当时说了,在那一篇咱们只讨论View的触摸事件派发机制,这个疑惑留在了这一篇解释,也就是ViewGroup的事件派发机制. PS:阅读本篇前建议先查看前一篇<Android触摸屏事件派发机制详解与源码分析一(View篇)>,这一篇承接上一篇. 关于View与ViewGroup的区别在前一篇的A

HashMap与TreeMap源码分析

1. 引言     在红黑树--算法导论(15)中学习了红黑树的原理.本来打算自己来试着实现一下,然而在看了JDK(1.8.0)TreeMap的源码后恍然发现原来它就是利用红黑树实现的(很惭愧学了Java这么久,也写过一些小项目,也使用过TreeMap无数次,但到现在才明白它的实现原理).因此本着"不要重复造轮子"的思想,就用这篇博客来记录分析TreeMap源码的过程,也顺便瞅一瞅HashMap. 2. 继承结构 (1) 继承结构 下面是HashMap与TreeMap的继承结构: pu

Linux内核源码分析--内核启动之(5)Image内核启动(rest_init函数)(Linux-3.0 ARMv7)【转】

原文地址:Linux内核源码分析--内核启动之(5)Image内核启动(rest_init函数)(Linux-3.0 ARMv7) 作者:tekkamanninja 转自:http://blog.chinaunix.net/uid-25909619-id-4938395.html 前面粗略分析start_kernel函数,此函数中基本上是对内存管理和各子系统的数据结构初始化.在内核初始化函数start_kernel执行到最后,就是调用rest_init函数,这个函数的主要使命就是创建并启动内核线