android啟動過程

來源:互聯網
上載者:User

標籤:

下面是android啟動到介面顯示流程圖




1:Linux核心啟動2:init進程啟動。3:本地系統服務,Java系統服務 啟動: 1):init啟動service manager,這個進程主要負責系統服務的註冊管理,包括“java系統服務”“本地系統服務” 2):init啟動Media server,這個進程負責啟動C/C++的“本地系統服務”。 3):init啟動Zygote,這個進程啟動System server進程,這個進程啟動"Java系統服務"---[包括power manager    service,sensor service] 4):另外init啟動system/bin下面的各種守護進程
4:Home啟動。
-------------------------------------------第一步:Linux核心啟動這個不祥細講
第二步:啟動Linux的第一個進程init

kernel/init/main.casmlinkage void __init start_kernel(void)//這是kernel的入口,head-common.S彙編代碼會串連過來。{    ......ftrace_init();/* Do the rest non-__init'ed, we're now alive */rest_init();}static noinline void __init_refok rest_init(void){......./* * We need to spawn init first so that it obtains pid 1, however * the init task will end up wanting to create kthreads, which, if * we schedule it before we create kthreadd, will OOPS. */kernel_thread(kernel_init, NULL, CLONE_FS | CLONE_SIGHAND);.......................}static int __init kernel_init(void * unused){.........if (!ramdisk_execute_command)<span style="color:#ff0000;">ramdisk_execute_command = "/init"</span>;//指定init檔案的位置if (sys_access((const char __user *) ramdisk_execute_command, 0) != 0) {ramdisk_execute_command = NULL;prepare_namespace();}/* * Ok, we have completed the initial bootup, and * we're essentially up and running. Get rid of the * initmem segments and start the user-mode stuff.. */init_post();return 0;}static noinline int init_post(void){/* need to finish all async __init code before freeing the memory */async_synchronize_full();free_initmem();mark_rodata_ro();system_state = SYSTEM_RUNNING;numa_default_policy();current->signal->flags |= SIGNAL_UNKILLABLE;if (ramdisk_execute_command) {run_init_process(ramdisk_execute_command);//調用run_init_process函數,init進程跑起來printk(KERN_WARNING "Failed to execute %s\n",ramdisk_execute_command);}...........}

第三步:啟動Service Manager進程
init進程通過init.rc配置啟動service manager進程
[init.rc]service servicemanager /system/bin/servicemanager//看到吧,    class core    user system    group system    critical    onrestart restart healthd    onrestart restart zygote    onrestart restart media    onrestart restart surfaceflinger    onrestart restart drmframeworks/native/cmds/servicemanager/service_manager.c//下面是進程代碼,他負責管理本地系統服務和java系統服務,為下面本地系統服務,java系統服務的註冊提供基礎。[c]void *do_find_service(struct binder_state *bs, uint16_t *s, unsigned len, unsigned uid){}int do_add_service(struct binder_state *bs,                   uint16_t *s, unsigned len,                   void *ptr, unsigned uid, int allow_isolated){}int main(int argc, char **argv){    struct binder_state *bs;    void *svcmgr = BINDER_SERVICE_MANAGER;    bs = binder_open(128*1024);    if (binder_become_context_manager(bs)) {        ALOGE("cannot become context manager (%s)\n", strerror(errno));        return -1;    }    svcmgr_handle = svcmgr;    binder_loop(bs, svcmgr_handler);    return 0;}


init進程通過init.rc配置啟動Media server
service media /system/bin/mediaserver    class main    user media    group audio camera inet net_bt net_bt_admin net_bw_acct drmrpc mediadrm qcom_diag    ioprio rt 4frameworks/av/media/mediaserver/main_mediaserver.cpp
//啟動一系列本地系統服務

</pre><pre>

[cpp]int main(int argc, char** argv){            ........        AudioFlinger::instantiate();        MediaPlayerService::instantiate();        CameraService::instantiate();#ifdef QCOM_LISTEN_FEATURE_ENABLE        ALOGI("ListenService instantiated");        ListenService::instantiate();#endif        AudioPolicyService::instantiate();#ifdef RESOURCE_MANAGER        ALOGI(" ResourceManagerService instantiated");        ResourceManagerService::instantiate();#endif        registerExtensions();        ProcessState::self()->startThreadPool();        IPCThreadState::self()->joinThreadPool();    }}

init進程通過init.rc配置啟動Zygote
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server//Zygote是通過app_process進程啟動的,注意:zygote是java代碼進程    class main    socket zygote stream 660 root system    onrestart write /sys/android_power/request_state wake    onrestart write /sys/power/state on    onrestart restart media    onrestart restart netd
frameworks/base/cmds/app_process/app_main.cpp[cpp]int main(int argc, char* const argv[]){<span style="color:#ff0000;">//建立android runtime,然後啟動Zygote進程</span>runtime.start("com.android.internal.os.ZygoteInit",                startSystemServer ? "start-system-server" : "");}frameworks/base/core/jni/AndroidRuntime.cppruntime裡建立虛擬機器,然後啟動Zygote進程void AndroidRuntime::start(const char* className, const char* options){    <span style="color:#ff0000;">//runtime建立虛擬機器,</span>    /* start the virtual machine */    JNIEnv* env;    if (startVm(&mJavaVM, &env) != 0) {        return;    }    onVmCreated(env);       //啟動java進程,上面講到的Zygote    /*     * Start VM.  This thread becomes the main thread of the VM, and will     * not return until the VM exits.     */    char* slashClassName = toSlashClassName(className);    jclass startClass = env->FindClass(slashClassName);    if (startClass == NULL) {        ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);        /* keep going */    } else {        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",            "([Ljava/lang/String;)V");        if (startMeth == NULL) {            ALOGE("JavaVM unable to find main() in '%s'\n", className);            /* keep going */        } else {            env->CallStaticVoidMethod(startClass, startMeth, strArray);#if 0            if (env->ExceptionCheck())                threadExitUncaughtException(env);#endif        }    }

Zygote啟動system server進程
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java public static void main(String argv[]) {        try {            // Start profiling the zygote initialization.            SamplingProfilerIntegration.start();           <span style="color:#ff0000;"> registerZygoteSocket();//註冊listner介面</span>            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,                SystemClock.uptimeMillis());            preload();            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,                SystemClock.uptimeMillis());            // 20131109 add for bootprof begin            addBootEvent(new String("Zygote:Preload Start"));// 20131109 add for bootprof end                        // Finish profiling the zygote initialization.            SamplingProfilerIntegration.writeZygoteSnapshot();            // Do an initial gc to clean up after startup            gc();            // Disable tracing so that forked processes do not inherit stale tracing tags from            // Zygote.            Trace.setTracingEnabled(false);            // If requested, start system server directly from Zygote            if (argv.length != 2) {                throw new RuntimeException(argv[0] + USAGE_STRING);            }            // 20131109 add for bootprof begin            addBootEvent(new String("Zygote:Preload End"));//20131109 add for bootprof end                        if (argv[1].equals("start-system-server")) {                startSystemServer();//啟動system server            } else if (!argv[1].equals("")) {                throw new RuntimeException(argv[0] + USAGE_STRING);            }            Log.i(TAG, "Accepting command socket connections");            runSelectLoop();            closeServerSocket();        } catch (MethodAndArgsCaller caller) {            caller.run();        } catch (RuntimeException ex) {            Log.e(TAG, "Zygote died with exception", ex);            closeServerSocket();            throw ex;        }    }

註:Zygote啟動system server進程,還註冊Scoket通道,接收來自ActivityManagerService的請求,Fork應用程式


frameworks/base/services/java/com/android/server/SystemServer.java//啟動一系列java系統服務public class SystemServer {    private static final String TAG = "SystemServer";.......    /**     * Called to initialize native system services.     */    private static native void nativeInit();    public static void main(String[] args) {.......// Initialize native services.        nativeInit();        // This used to be its own separate thread, but now it is        // just the loop we run on the main thread.        ServerThread thr = new ServerThread();        thr.initAndLoop();    }}class ServerThread {    private static final String TAG = "SystemServer";    private static final String ENCRYPTING_STATE = "trigger_restart_min_framework";    private static final String ENCRYPTED_STATE = "1";    ContentResolver mContentResolver;    void reportWtf(String msg, Throwable e) {        Slog.w(TAG, "***********************************************");        Log.wtf(TAG, "BOOT FAILURE " + msg, e);    }    public void initAndLoop() {.....Slog.i(TAG, "Content Manager");            contentService = ContentService.main(context,                    factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);            Slog.i(TAG, "System Content Providers");            ActivityManagerService.installSystemProviders();            Slog.i(TAG, "Lights Service");            lights = new LightsService(context);            Slog.i(TAG, "Battery Service");            battery = new BatteryService(context, lights);            ServiceManager.addService("battery", battery);            Slog.i(TAG, "Vibrator Service");            vibrator = new VibratorService(context);            ServiceManager.addService("vibrator", vibrator);            Slog.i(TAG, "Consumer IR Service");            consumerIr = new ConsumerIrService(context);            ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);.......}}


第四步 Home啟動


frameworks/base/services/java/com/android/server/am/ActivityManagerService.javasystem server啟動java系統服務後,會發出systemRready的通知。ActivityManagerService的SystemReady函數回調發出UserSwitch的廣播啟動Home   public void systemReady(final Runnable goingCallback) {        synchronized(this) {            if (mSystemReady) {                if (goingCallback != null) goingCallback.run();                return;            }            mStackSupervisor.resumeTopActivitiesLocked();            sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);        }    }    @Override    public boolean switchUser(final int userId) {boolean homeInFront = mStackSupervisor.switchUserLocked(userId, uss);                if (homeInFront) {                    <span style="color:#ff0000;">startHomeActivityLocked(userId);</span>                } else {                    mStackSupervisor.resumeTopActivitiesLocked();                }}









android啟動過程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.