码迷,mamicode.com
首页 > 移动开发 > 详细

android启动过程

时间:2014-12-26 16:42:58      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:

下面是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.c

asmlinkage 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 drm

frameworks/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 4

frameworks/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.cpp
runtime里建立虚拟机,然后启动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.java


system 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启动过程

标签:

原文地址:http://blog.csdn.net/hovan/article/details/42172481

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!