android启动流程

下面是android启动到界面显示流程图


android启动流程_第1张图片


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)
		ramdisk_execute_command = "/init";//指定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[])
{
//建立android runtime,然后启动Zygote进程
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)
{
    
//runtime建立虚拟机,
    /* 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();

            registerZygoteSocket();//注册listner接口
            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系统服务后
ActivityManagerService的SystemReady函数回调

   public void systemReady(final Runnable goingCallback) {
        synchronized(this) {
            if (mSystemReady) {
                if (goingCallback != null) goingCallback.run();
                return;
            }
            mStackSupervisor.resumeTopActivitiesLocked();//启动HomeActivity
            sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
        }
    }


mStackSuperVisor.resumeTopActivitiesLocked()实现


frameworks/base/services/java/com/android/server/am/ActivityStackSupervisor.java

 boolean resumeTopActivitiesLocked() {
        return resumeTopActivitiesLocked(null, null, null);
    }

    boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
            Bundle targetOptions) {
        if (targetStack == null) {
            targetStack = getFocusedStack();
        }
        boolean result = false;
        for (int stackNdx = mStacks.size() - 1; stackNdx >= 0; --stackNdx) {
            final ActivityStack stack = mStacks.get(stackNdx);
            if (isFrontStack(stack)) {
                if (stack == targetStack) {
                    result = stack.resumeTopActivityLocked(target, targetOptions);
                } else {
                    stack.resumeTopActivityLocked(null);//调用ActivityStack::resumeTopActivityLocked()
                }
            }
        }
        return result;
    }

这时mStacks.size()=1,为什么呢?

因为systemserver进程调用setWindowManager(wm)创建了第一个ActivityStack,并且是HOME_STACK.

frameworks/base/services/java/com/android/server/SystemServer.java

public void initAndLoop() { 
...
ActivityManagerService.self().setWindowManager(wm);
...
}


ActivityManagerService.setWindowManager()的实现

frameworks/base/services/java/com/android/server/am/ActivityManagerService.java

    public void setWindowManager(WindowManagerService wm) {
        mWindowManager = wm;
        mStackSupervisor.setWindowManager(wm);//调用
        wm.createStack(HOME_STACK_ID, -1, StackBox.TASK_STACK_GOES_OVER, 1.0f);
    }


mStackSupervisor.setWindowManager()的实现

frameworks/base/services/java/com/android/server/am/ActivityStackSupervisor.java
    void setWindowManager(WindowManagerService wm) {
        mWindowManager = wm;
        mHomeStack = new ActivityStack(mService, mContext, mLooper, HOME_STACK_ID);//创建了一个<span style="font-family: Arial, Helvetica, sans-serif;">ActivityStack</span>,并add入mStack变量
        mStacks.add(mHomeStack);
    }

这里创建了第一个ActivityStack,并且ID=HOME_STACK_ID.

所以mStacks.size()=1就是HOME也是Launcher。


回到刚才的函数

frameworks/base/services/java/com/android/server/am/ActivityStackSupervisor.java

    boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
            Bundle targetOptions) {
        .....
            if (isFrontStack(stack)) {
                if (stack == targetStack) {
                    result = stack.resumeTopActivityLocked(target, targetOptions);
                } else {
                    stack.resumeTopActivityLocked(null);//调用ActivityStack::resumeTopActivityLocked()
                }
            }
      .....
    }

然后由于传进来的targetStack=null,所以会走else,调用stack.resumeTopActivityLocked(null).


stack.resumeTopActivityLocked(null)的实现

frameworks/base/services/java/com/android/server/am/ActivityStack.java

final boolean resumeTopActivityLocked(ActivityRecord prev) {
        return resumeTopActivityLocked(prev, null);
    }

    final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
        if (ActivityManagerService.DEBUG_LOCKSCREEN) mService.logLockScreen("");

        // Find the first activity that is not finishing.
        ActivityRecord next = topRunningActivityLocked(null);

        // Remember how we'll process this pause/resume situation, and ensure
        // that the state is reset however we wind up proceeding.
        final boolean userLeaving = mStackSupervisor.mUserLeaving;
        mStackSupervisor.mUserLeaving = false;

        if (next == null) {
            // There are no more activities!  Let's just start up the
            // Launcher...
            ActivityOptions.abort(options);
            if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: No more activities go home");
            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
            return mStackSupervisor.resumeHomeActivity(prev);//调用
        }

prev=null,由于Launcher是第一个ActivityStack,所以next = null


那么就调用mStackSupervisor.resumeHomeActivity(prev)来启动Launcher。


frameworks/base/services/java/com/android/server/am/ActivityStackSupervisor.java

boolean resumeHomeActivity(ActivityRecord prev) {
        moveHomeToTop();
        if (prev != null) {
            prev.task.mOnTopOfHome = false;
        }
        ActivityRecord r = mHomeStack.topRunningActivityLocked(null);
        if (r != null && r.isHomeActivity()) {
            mService.setFocusedActivityLocked(r);
            return resumeTopActivitiesLocked(mHomeStack, prev, null);
        }
        return mService.startHomeActivityLocked(mCurrentUser);//这里
    }


由于Home还没有跑起来,所以r=null,那么就跑mService.startHomeActivityLocked(mCurrentUser);实现如下


frameworks/base/services/java/com/android/server/am/ActivityManagerService.java

boolean startHomeActivityLocked(int userId) {
        if (mHeadless) {
            // Added because none of the other calls to ensureBootCompleted seem to fire
            // when running headless.
            ensureBootCompleted();
            return false;
        }

        if (mFactoryTest == SystemServer.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;
    }










你可能感兴趣的:(android启动流程)