Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android系統教程 >> Android開發教程 >> Android源碼之SurfaceFlinger的起動(一)

Android源碼之SurfaceFlinger的起動(一)

編輯:Android開發教程

Android源碼之SurfaceFlinger的啟動(一)
page1
在Android系統中, 顯示系統在底層是通過SurfaceFlinger服務來完成的, 因此從今天開始, 我們從SurfaceFlinger服務作為入口來分析一下Android顯示系統.
SurfaceFlinger服務是在System進程中, 而System進程是由Zygote進程啟動的, 並且是以Java層的SystemServer類的靜態成員函數main為入口函數的。
因此,接下來我們就從SystemServer類(定義在SystemServer.java文件中)的靜態成員函數main開始,分析SurfaceFlinger服務的啟動過程:
1 public static void main(String[] args) {
    2    if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
    3        // If a device's clock is before 1970 (before 0), a lot of
    4        // APIs crash dealing with negative numbers, notably
    5        // java.io.File#setLastModified, so instead we fake it and
    6        // hope that time from cell towers or NTP fixes it
    7        // shortly.
    8        Slog.w(TAG, "System clock is before 1970; setting to 1970.");
    9        SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
    10    }

    11    if (SamplingProfilerIntegration.isEnabled()) {
    12        SamplingProfilerIntegration.start();
    13        timer = new Timer();
    14        timer.schedule(new TimerTask() {
    15            @Override
    16            public void run() {
    17                SamplingProfilerIntegration.writeSnapshot("system_server", null);
    18            }
    19        }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
    20    }

        // Mmmmmm... more memory!
    21    dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();

        // The system server has to run all of the time, so it needs to be
        // as efficient as possible with its memory usage.
    22    VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

    23    System.loadLibrary("android_servers");
    24    init1(args);
    25 }
第24行(SystemServer.main)會調用init1函數來進行初始化操作, init1函數是個native函數來初始化C++層的服務, 會導致com_android_server_SystemServer.cpp的android_server_SystemServer_init1函數的調用, 關於com_android_server_SystemServer.cpp的android_server_SystemServer_init1函數的詳細分析可以參考page2文件.

page2
1static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
2{
3 system_init();
4}
第3行(com_android_server_SystemServer->android_server_SystemServer_init1)會調用system_init函數, system_init函數是在system_init.cpp文件中定義的, system_init函數的定義如下:
1extern "C" status_t system_init()
2{
3 ALOGI("Entered system_init()");
4 sp<ProcessState> proc(ProcessState::self());
5 sp<IServiceManager> sm = defaultServiceManager();
6 ALOGI("ServiceManager: %p\n", sm.get());
7 sp<GrimReaper> grim = new GrimReaper();
8 sm->asBinder()->linkToDeath(grim, grim.get(), 0);

9 char propBuf[PROPERTY_VALUE_MAX];
10 property_get("system_init.startsurfaceflinger", propBuf, "1");
11 if (strcmp(propBuf, "1") == 0) {
12 // Start the SurfaceFlinger
13 SurfaceFlinger::instantiate();
14 }

15 property_get("system_init.startsensorservice", propBuf, "1");
16 if (strcmp(propBuf, "1") == 0) {
17 // Start the sensor service
18 SensorService::instantiate();
19 }

// And now start the Android runtime.  We have to do this bit
// of nastiness because the Android runtime initialization requires
// some of the core system services to already be started.
// All other servers should just start the Android runtime at
// the beginning of their processes's main(), before calling
// the init function.
20 ALOGI("System server: starting Android runtime.\n");
21 AndroidRuntime* runtime = AndroidRuntime::getRuntime();

22 ALOGI("System server: starting Android services.\n");
23 JNIEnv* env = runtime->getJNIEnv();
24 if (env == NULL) {
25 return UNKNOWN_ERROR;
26 }
27 jclass clazz = env->FindClass("com/android/server/SystemServer");
28 if (clazz == NULL) {
29 return UNKNOWN_ERROR;
30 }
31 jmethodID methodId = env->GetStaticMethodID(clazz, "init2", "()V");
32 if (methodId == NULL) {
33 return UNKNOWN_ERROR;
34 }
35 env->CallStaticVoidMethod(clazz, methodId);

36 ALOGI("System server: entering thread pool.\n");
37 ProcessState::self()->startThreadPool();
38 IPCThreadState::self()->joinThreadPool();
39 ALOGI("System server: exiting thread pool.\n");

40 return NO_ERROR;
41 }
第9-14行(system_init->system_init)如果發現系統屬性中設置了啟動SurfaceFlinger服務, 第13行(system_init->system_init)會調用SurfaceFlinger的instantiate函數來啟動SurfaceFlinger服務, 關於SurfaceFlinger的instantiate的詳細分析可以參考page3文件.
第37-38行(system_init->system_init)是啟動Binder的線程池, 從此開始, SystemServer進程就可以接受Binder的進程間通信了.
page3
我們從SurfaceFlinger的instantiate函數作為入口來分析SurfaceFinger服務的啟動.
我們先來看一下SurfaceFlinger類的繼承體系:
class SurfaceFlinger : public BinderService<SurfaceFlinger>,
                           public BnSurfaceComposer,
                           private IBinder::DeathRecipient,
                           private Thread,
                           private HWComposer::EventHandler

    我靠!SurfaceFlinger繼承了5個父類.
    不管了, 先分析instantiate函數, instantiate函數是從BinderService繼承而來的, 我們先來看一下BinderService類的聲明:
    template<typename SERVICE> class BinderService
    BinderService接受一個模板參數.
    BinderService的instantiate函數定義如下:
    static void instantiate() {
        publish();
    }

    instantiate函數只是調用了publish函數, publish函數的定義如下:
    1    static status_t publish(bool allowIsolated = false) {
    2        sp<IServiceManager> sm(defaultServiceManager());
    3        return sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);
    4    }
    第2行(BinderService->publish)獲得ServiceManager.
    第3行(BinderService->publish)會new一個SERVICE實例, 並調用ServiceManager的addService函數來交給ServiceManager管理, 這是Binder機制的基礎.
    因此這裡會new一個SurfaceFlinger對象, 關於SurfaceFlinger的構造函數的分析可以參考page4文件.
    因為ServiceManager的addService函數的參數是個SP類型的, 因此這裡會導致SurfaceFlinger的onFirstRef函數的調用, onFirstRef函數的定義如下:
    1void SurfaceFlinger::onFirstRef()
    2{
    3    mEventQueue.init(this);
    4
    5    run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
    6
    7    // Wait for the main thread to be done with its initialization
    8    mReadyToRunBarrier.wait();
    9}
    第3行(SurfaceFlinger->onFirstRef)成員變量mEventQueue是一個MessageQueue類型的, 因此這裡會調用MessageQueue的init函數. 關於MessageQueue的init函數的實現可以參考page5文件.
    第5行(SurfaceFlinger->onFirstRef)會調用run函數, run函數是從Thread類繼承下來的. 關於Thread的run函數的詳細分析可以參考page6文件.
page4
我們分析一下SurfaceFlinger的構造函數的實現:
    1 SurfaceFlinger::SurfaceFlinger()
    2     :   BnSurfaceComposer(), Thread(false),
    3         mTransactionFlags(0),
    4         mTransactionPending(false),
    5         mAnimTransactionPending(false),
    6         mLayersRemoved(false),
    7         mRepaintEverything(0),
    8         mBootTime(systemTime()),
    9         mVisibleRegionsDirty(false),
    10         mHwWorkListDirty(false),
    11         mDebugRegion(0),
    12         mDebugDDMS(0),
    13         mDebugDisableHWC(0),
    14         mDebugDisableTransformHint(0),
    15         mDebugInSwapBuffers(0),
    16         mLastSwapBufferTime(0),
    17         mDebugInTransaction(0),
    18         mLastTransactionTime(0),
    19         mBootFinished(false)
    20 {
    21     ALOGI("SurfaceFlinger is starting");
    22
    23     // debugging stuff...
    24     char value[PROPERTY_VALUE_MAX];
    25
    26     property_get("debug.sf.showupdates", value, "0");
    27     mDebugRegion = atoi(value);
    28
    29     property_get("debug.sf.ddms", value, "0");
    30     mDebugDDMS = atoi(value);
    31     if (mDebugDDMS) {
    32         if (!startDdmConnection()) {
    33             // start failed, and DDMS debugging not enabled
    34             mDebugDDMS = 0;
    35         }
    36     }
    37     ALOGI_IF(mDebugRegion, "showupdates enabled");
    38     ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
    39 }

    可以看到, SurfaceFlinger的構造函數除了初始化成員變量之外, 沒有什麼額外的邏輯.
page5
我們分析一下MessageQueue的init函數的實現, 如下所示:
1void MessageQueue::init(const sp<SurfaceFlinger>& flinger)
    2{
    3    mFlinger = flinger;
    4    mLooper = new Looper(true);
    5    mHandler = new Handler(*this);
    6}
    第3行(MessageQueue->init)會將SurfaceFlinger對象保存到MessageQueue裡.
    第4行(MessageQueue->init)會new一個Looper對象, 用於分發消息.
    第5行(MessageQueue->init)會用本MessageQueue去初始化一個Handler對象, 注意, Handler是在MessageQueue類裡定義的一個內部類, 定義如下:

    class Handler : public MessageHandler {
            enum {
                eventMaskInvalidate = 0x1,
                eventMaskRefresh    = 0x2
            };
            MessageQueue& mQueue;
            int32_t mEventMask;
        public:
            Handler(MessageQueue& queue) : mQueue(queue), mEventMask(0) { }
            virtual void handleMessage(const Message& message);
            void dispatchRefresh();
            void dispatchInvalidate();
    };
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved