Android应用启动流程分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/heimaer/article/details/84098739

从系统桌面 LauncherActivity 开始 基于API_15

  • LauncherActivity 内部其实就是用ListView把已经安装好的应用显示出来,那我们最关心的是什么呢,当然是从点击桌面的图标之后到底发生了什么
	public abstract class LauncherActivity extends ListActivity {
    Intent mIntent;
    PackageManager mPackageManager;
    IconResizer mIconResizer;
    
    /**
     * An item in the list
     */
    public static class ListItem {
        public ResolveInfo resolveInfo;
        public CharSequence label;
        public Drawable icon;
        public String packageName;
        public String className;
        public Bundle extras;
        。。。
    }
    private class ActivityAdapter extends BaseAdapter implements Filterable {
	    。。。
    }
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        mPackageManager = getPackageManager();
        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_WATCH)) {
            requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
            setProgressBarIndeterminateVisibility(true);
        }
    	。。。
        mAdapter = new ActivityAdapter(mIconResizer);
        setListAdapter(mAdapter);
        getListView().setTextFilterEnabled(true);
    }
    @Override 
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	//ListView的点击事件也就是桌面的Icon的点击事件 ,这是整个启动流程的时间启动源。
        Intent intent = intentForPosition(position);
        startActivity(intent);
    }
     public Intent intentForPosition(int position) {
            Intent intent = new Intent(mIntent);
            ListItem item = mActivitiesList.get(position);
            intent.setClassName(item.packageName, item.className);
            if (item.extras != null) {
                intent.putExtras(item.extras);
            }
            return intent;
        }
}

从以上主要代码中我们不难看出

  • LauncherActivity 中其实就是ListView把已经安装的应用展示出来,
  • 在点击Item的时候,获取Item的信息并创建Intent,最后走Activity的startActivity()方法;
    系统桌面的情况大致是这样,那我们继续往下走,开启这个Activity又干了什么,是如何把整个应用开启起来的。

进入startActivity

 @Override
    public void startActivity(Intent intent) {
        startActivityForResult(intent, -1);
    }
 public void startActivityForResult(Intent intent, int requestCode) {
 	//  Activity mParent;  其实是一个Activity ,判断是否有父类,没有父类的话交给Instrumentation
        if (mParent == null) {
            Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this,  intent,requestCode);
            if (ar != null) {
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
            if (requestCode >= 0) {
                mStartedActivity = true;
            }
        } else {
            mParent.startActivityFromChild(this, intent, requestCode);
        }
    }

 public void startActivityFromChild(Activity child, Intent intent, 
            int requestCode) {
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, child,
                intent, requestCode);
        if (ar != null) {
            mMainThread.sendActivityResult(
                mToken, child.mEmbeddedID, requestCode,
                ar.getResultCode(), ar.getResultData());
        }
    }
  • 不难发现,不论有没有父Activity最终都交给了 Instrumentation来开启 ,走到这里还是没有看到,那么不要泄气继续往下走一步看看

进入instrumentation

 public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
        if (mActivityMonitors != null) {
            synchronized (mSync) {
                final int N = mActivityMonitors.size();
                for (int i=0; i<N; i++) {
                    final ActivityMonitor am = mActivityMonitors.get(i);
                    if (am.match(who, null, intent)) {
                        am.mHits++;
                        if (am.isBlocking()) {
                            return requestCode >= 0 ? am.getResult() : null;
                        }
                        break;
                    }
                }
            }
        }
        try {
            intent.setAllowFds(false);
            //  这里又交给了  ActivityManagerNative.getDefault()  他,他我们并不是很陌生的,你肯定猜到了。
            int result = ActivityManagerNative.getDefault()
                .startActivity(whoThread, intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        null, 0, token, target != null ? target.mEmbeddedID : null,
                        requestCode, false, false, null, null, false);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
        }
        return null;
    }

进入 ActivityManager

首先我们看 ActivityManagerNative 有啥神操作

static public IActivityManager getDefault() {
继续追踪ActivityManager
        return ActivityManager.getService();
    }
    //ActivityManager 
public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }
private static final Singleton<IActivityManager> IActivityManagerSingleton =
         new Singleton<IActivityManager>() {
             @Override
             protected IActivityManager create() {
             //IPC操刀,获取通过系统的  ServiceManager 类  获取到一个IBinder对象并转换成  IActivityManager  也就是说我们上面的
             ActivityManagerNative.getDefault()  最终获取的就是一个 IActivityManager  ,最终的启动流程在 IActivityManager  这个里面。
                 final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                 final IActivityManager am = IActivityManager.Stub.asInterface(b);
                 return am;
             }
         };
  • 我们最终定位到了 IActivityManager 但是我们发现到这个类已经无法操刀了,IPC的机制,她只是一个
    IActivityManager extends IInterface 一个IPC操作,并不是真正执行 开启页面你的地方,但我们知道他获取的是一个啥啊,不就是ActivityManagerService吗,咱不是好骗的,直接奔ActivityManagerservice 去。

进入ActivityManagerService

public final int startActivity(IApplicationThread caller,
            Intent intent, String resolvedType, IBinder resultTo,
            String resultWho, int requestCode, int startFlags,
            String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
        enforceNotIsolatedCaller("startActivity");
        int userId = 0;
        if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
            userId = mCurrentUserId;
        } else {
            if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
                userId = 0;
            } else {
                userId = Binder.getOrigCallingUser();
            }
        }
        //最后又走了mMainStack的方法, 藏的忒深了,让**好找啊,进去瞅瞅
        return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
                resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
                null, null, options, userId);
    }

进入ActivityStack

//这次就不全贴代码了太长了,但是这个类至关重要,决定了冷热启动 
  final int startActivityMayWait(...) {
}

private final void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid);
	...
	//这个方法就很重要了不是,我们可以很明显的发现,他是用来进行判断冷启动和热启动的,
	如果进程存在那么就开启activiy如果不存在那就调用开启进程的方法
        if (app != null && app.thread != null) {
            try {
                app.addPackage(r.info.packageName);
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            } 
        }
	
        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                "activity", r.intent.getComponent(), false, false);
    }

进入ActivityStack

//这次就不全贴代码了太长了,但是这个类至关重要,决定了冷热启动 
  final int startActivityMayWait(...) {
   ...
        int res = startActivityLocked(caller, intent, resolvedType,
             aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
             startFlags, options, componentSpecified, null);
}
//  紧接着调用了一系列方法,直至startSpecificActivityLocked 方法
-> startActivityMayWait
-> startActivityLocked
-> startActivityUncheckedLocked
-> targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options)
-> mStackSupervisor.resumeTopActivitiesLocked(this, r, options)
-> resumeTopActivityInnerLocked(prev, options);
-> mStackSupervisor.startSpecificActivityLocked(next, true, true)
//我们最后来看 startSpecificActivityLocked这个方法干了什么
private final void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid);
	...
	//这个方法就很重要了不是,我们可以很明显的发现,他是用来进行判断冷启动和热启动的,
	如果进程存在那么就开启activiy如果不存在那就调用开启进程的方法
        if (app != null && app.thread != null) {
            try {
                app.addPackage(r.info.packageName);
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            } 
        }
	//没有进程的时候最终还是交给了ActivityManagerService 
        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                "activity", r.intent.getComponent(), false, false);
    }
  • 到了这就分了两条路走了不是,我么还是从最原始的那一条开始吧,先看如何开启进程的

回到ActivityManagerService开启进程

final ProcessRecord startProcessLocked(String processName,
            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
            String hostingType, ComponentName hostingName, boolean allowWhileBooting,
            boolean isolated) {
        ProcessRecord app;
        if (!isolated) {//第一次进来的时候是false  进入获取进程
            app = getProcessRecordLocked(processName, info.uid);
        } else {
            app = null;
        }
        if (app != null && app.pid > 0) {
            if (!knownToBeDead || app.thread == null) {
                app.addPackage(info.packageName);
                return app;
            } else {
                handleAppDiedLocked(app, true, true);
            }
        }
        if (!isolated) {
            if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
                if (mBadProcesses.get(info.processName, info.uid) != null) {
                    return null;
                }
            } else {
                mProcessCrashTimes.remove(info.processName, info.uid);
                if (mBadProcesses.get(info.processName, info.uid) != null) {
                    mBadProcesses.remove(info.processName, info.uid);
                    if (app != null) {
                        app.bad = false;
                    }
                }
            }
        }
	//如果获取不到进程信息就创建一个,并绑定了相关应用信息
        if (app == null) {
            app = newProcessRecordLocked(null, info, processName, isolated);
            mProcessNames.put(processName, app.uid, app);
            if (isolated) {
                mIsolatedProcesses.put(app.uid, app);
            }
        } else {
            app.addPackage(info.packageName);
        }
        if (!mProcessesReady
                && !isAllowedWhileBooting(info)
                && !allowWhileBooting) {
            if (!mProcessesOnHold.contains(app)) {
                mProcessesOnHold.add(app);
            }
            return app;
        }
        startProcessLocked(app, hostingType, hostingNameStr);
        return (app.pid != 0) ? app : null;
    }

进入 Process

 public static final ProcessStartResult start(。。。) {
        try {
        // 到这貌似就熟悉了,就是我们通常说的Zygote fork app进程的那一套  走两步瞅瞅吧
            return startViaZygote(processClass, niceName, uid, gid, gids,
                    debugFlags, targetSdkVersion, zygoteArgs);
        } catch (ZygoteStartFailedEx ex) {
        }
    }
    -> zygoteSendArgsAndGetResult()
     private static ProcessStartResult zygoteSendArgsAndGetResult(ArrayList<String> args)
            throws ZygoteStartFailedEx {
            //到了我们最长听到的Zygote
        openZygoteSocketIfNeeded();
        //就是 开启了一个socket进行通信的
      //   sZygoteSocket = new LocalSocket();
         onnect(new LocalSocketAddress(ZYGOTE_SOCKET, 
                        LocalSocketAddress.Namespace.RESERVED)); 

            ProcessStartResult result = new ProcessStartResult();
            result.pid = sZygoteInputStream.readInt();
            result.usingWrapper = sZygoteInputStream.readBoolean();
            return result;
        } catch (IOException ex) {
            try {
                if (sZygoteSocket != null) {
                    sZygoteSocket.close();
                }
            } catch (IOException ex2) {
            }
        }
    }
  • 迷雾重重,我们到这里看到了一些东西,但是似乎还没有尽兴,那我们继续 Zygote是如何fork一个进程的,我们刚才看到他开启了一个socket用来同信,那么我们走进ZygoteInit类里面看看

进入ZygoteInit

public static void main(String argv[]) {
        try {
            SamplingProfilerIntegration.start();
		//注册socket服务端
            registerZygoteSocket();
            //加载 class  resource  dawable等资源
            preload();
            SamplingProfilerIntegration.writeZygoteSnapshot();
            gc();
            //从这里开启了 SystemServer进程  , 一定要注意,本文基于api15  
            if (argv[1].equals("start-system-server")) {
                startSystemServer();
            } else if (!argv[1].equals("")) {
                throw new RuntimeException(argv[0] + USAGE_STRING);
            }
            if (ZYGOTE_FORK_MODE) {
                runForkMode();
            } else {
            //等待ActivityManagerService的请求
                runSelectLoopMode();
            }
            closeServerSocket();
        } catch (MethodAndArgsCaller caller) {
            caller.run();
        } catch (RuntimeException ex) {
            closeServerSocket();
            throw ex;
        }
    }

// 如何Fork SystemServer 进程  ,至于SsytemServer 我想后面再讲
private static boolean startSystemServer() {
        ZygoteConnection.Arguments parsedArgs = null;
        int pid;
        try {
            parsedArgs = new ZygoteConnection.Arguments(args);
            ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
            ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
            pid = Zygote.forkSystemServer(
                    parsedArgs.uid, parsedArgs.gid,
                    parsedArgs.gids,
                    parsedArgs.debugFlags,
                    null,
                    parsedArgs.permittedCapabilities,
                    parsedArgs.effectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }
         /* For child process */
        if (pid == 0) {
            handleSystemServerProcess(parsedArgs);
        }
        return true;
    }
// 当然最终fork是native层的东东
public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,
            int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
        VM_HOOKS.preFork();
        // Resets nice priority for zygote process.
        resetNicePriority();
        int pid = nativeForkSystemServer(
                uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);
        // Enable tracing as soon as we enter the system_server.
        if (pid == 0) {
            Trace.setTracingEnabled(true);
        }
        VM_HOOKS.postForkCommon();
        return pid;
    }
  • 到这还是没有看到最后,我们先不管SystemServer干了什么,先走完,我们现在唯一要寻找的是什么不能忘记啊,是ActivityThread开启的地方,不是吗? 继续
 private static void handleSystemServerProcess(
            ZygoteConnection.Arguments parsedArgs)
            throws Zygote.MethodAndArgsCaller {
        Os.umask(S_IRWXG | S_IRWXO);
        if (parsedArgs.niceName != null) {
            Process.setArgV0(parsedArgs.niceName);
        }
        final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
        if (systemServerClasspath != null) {
            performSystemServerDexOpt(systemServerClasspath);
            boolean profileSystemServer = SystemProperties.getBoolean(
                    "dalvik.vm.profilesystemserver", false);
            if (profileSystemServer && (Build.IS_USERDEBUG || Build.IS_ENG)) {
                try {
                    File profileDir = Environment.getDataProfilesDePackageDirectory(
                            Process.SYSTEM_UID, "system_server");
                    File profile = new File(profileDir, "primary.prof");
                    profile.getParentFile().mkdirs();
                    profile.createNewFile();
                    String[] codePaths = systemServerClasspath.split(":");
                    VMRuntime.registerAppInfo(profile.getPath(), codePaths);
                } catch (Exception e) {
                    Log.wtf(TAG, "Failed to set up system server profile", e);
                }
            }
        }
        if (parsedArgs.invokeWith != null) {
            String[] args = parsedArgs.remainingArgs;
            if (systemServerClasspath != null) {
                String[] amendedArgs = new String[args.length + 2];
                amendedArgs[0] = "-cp";
                amendedArgs[1] = systemServerClasspath;
                System.arraycopy(args, 0, amendedArgs, 2, args.length);
                args = amendedArgs;
            }
            WrapperInit.execApplication(parsedArgs.invokeWith,
                    parsedArgs.niceName, parsedArgs.targetSdkVersion,
                    VMRuntime.getCurrentInstructionSet(), null, args);
        } else {
            ClassLoader cl = null;
            if (systemServerClasspath != null) {
                cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);
                Thread.currentThread().setContextClassLoader(cl);
            }
            //又回来了 ,绕啊绕,坚持,黎明前最后的黑暗了
            ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
        }
    }

// 进入ZygoteInit  
public static final void zygoteInit(int targetSdkVersion, String[] argv,
            ClassLoader classLoader) throws Zygote.MethodAndArgsCaller {
      Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
        RuntimeInit.redirectLogStreams();

        RuntimeInit.commonInit();
        ZygoteInit.nativeZygoteInit();
        //就是你
        RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
    } 

进入RuntimeInit

 protected static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
            throws Zygote.MethodAndArgsCaller {
        nativeSetExitWithoutCleanup(true);

        // We want to be fairly aggressive about heap utilization, to avoid
        // holding on to a lot of memory that isn't needed.
        VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
        VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);

        final Arguments args;
        try {
            args = new Arguments(argv);
        } catch (IllegalArgumentException ex) {
            Slog.e(TAG, ex.getMessage());
            // let the process exit
            return;
        }
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        invokeStaticMain(args.startClass, args.startArgs, classLoader);
    }

// 继续
private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
            throws Zygote.MethodAndArgsCaller {
        Class<?> cl;
        try {
            cl = Class.forName(className, true, classLoader);
        } 
        Method m;
        try {
            m = cl.getMethod("main", new Class[] { String[].class });
        } 
        int modifiers = m.getModifiers();
        if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
            throw new RuntimeException(
                    "Main method is not public and static on " + className);
        }
        // 玩法很新颖,刚开始误以为抛个异常,结果没发现,居然是方法的执行地,
        throw new Zygote.MethodAndArgsCaller(m, argv);
    }

 public static class MethodAndArgsCaller extends Exception
            implements Runnable {
        private final Method mMethod;
        private final String[] mArgs;

        public MethodAndArgsCaller(Method method, String[] args) {
            mMethod = method;
            mArgs = args;
        }
        public void run() {
            try {
            	// 这里的 main正式 ActivityThread的main方法,到了这里,我们已经找到了程序的入口了
                mMethod.invoke(null, new Object[] { mArgs });
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

  • 我们最终在 RuntimeInit 中找到了利用反射调用ActivityThread的main方法的地方,到了这里我们主要走的流程已经很清楚了,但是SystemServer好想还是没弄清楚,到底干了啥进去瞅瞅吧

SystemServer 简略

public class SystemServer {
    private static final String TAG = "SystemServer";
    public static final int FACTORY_TEST_OFF = 0;
    public static final int FACTORY_TEST_LOW_LEVEL = 1;
    public static final int FACTORY_TEST_HIGH_LEVEL = 2;

    static Timer timer;
    static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; 
    private static final long EARLIEST_SUPPORTED_TIME = 86400 * 1000;
    native public static void init1(String[] args);

    public static void main(String[] args) {
        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
        }

        if (SamplingProfilerIntegration.isEnabled()) {
            SamplingProfilerIntegration.start();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    SamplingProfilerIntegration.writeSnapshot("system_server", null);
                }
            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
        }
        dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

        System.loadLibrary("android_servers");
        init1(args);
    }

    public static final void init2() {
     	//我们发现除了这个其他的操作并没有很清楚的看到干了我们能明白的事情,那我们进入这里看看
        Thread thr = new ServerThread();
        thr.setName("android.server.ServerThread");
        thr.start();
    }
}

ServerThread

//既然是一个 Thread直接看run里面干了什么吧
public void run() {
    	//这个版本的SystemServer看着没那么明白,高版本的特别清楚,主要工作无非是开启了很多服务,例如 我们的电池 位置  等等    ServiceManager.addService  来进行添加,前面我们见到的ActivityManagerService 怎么取的,不就是  ServiceManager获取的吗
        // Critical services...
        try {
            Slog.i(TAG, "Entropy Mixer");
            ServiceManager.addService("entropy", new EntropyMixer());

            Slog.i(TAG, "Power Manager");
            power = new PowerManagerService();
            ServiceManager.addService(Context.POWER_SERVICE, power);

            Slog.i(TAG, "Activity Manager");
            context = ActivityManagerService.main(factoryTest);

            Slog.i(TAG, "Telephony Registry");
            ServiceManager.addService("telephony.registry", new TelephonyRegistry(context));

            Slog.i(TAG, "Scheduling Policy");
            ServiceManager.addService(Context.SCHEDULING_POLICY_SERVICE,
                    new SchedulingPolicyService());

            AttributeCache.init(context);

            Slog.i(TAG, "Package Manager");
            // Only run "core" apps if we're encrypting the device.
            String cryptState = SystemProperties.get("vold.decrypt");
            boolean onlyCore = false;
            if (ENCRYPTING_STATE.equals(cryptState)) {
                Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
                onlyCore = true;
            } else if (ENCRYPTED_STATE.equals(cryptState)) {
                Slog.w(TAG, "Device encrypted - only parsing core apps");
                onlyCore = true;
            }

            pm = PackageManagerService.main(context,
                    factoryTest != SystemServer.FACTORY_TEST_OFF,
                    onlyCore);
            boolean firstBoot = false;
            try {
                firstBoot = pm.isFirstBoot();
            } catch (RemoteException e) {
            }

            ActivityManagerService.setSystemProcess();

            mContentResolver = context.getContentResolver();

            // The AccountManager must come before the ContentService
            try {
                Slog.i(TAG, "Account Manager");
                ServiceManager.addService(Context.ACCOUNT_SERVICE,
                        new AccountManagerService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Account Manager", e);
            }

            Slog.i(TAG, "Content Manager");
            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);

            // only initialize the power service after we have started the
            // lights service, content providers and the battery service.
            power.init(context, lights, ActivityManagerService.self(), battery);

            Slog.i(TAG, "Alarm Manager");
            alarm = new AlarmManagerService(context);
            ServiceManager.addService(Context.ALARM_SERVICE, alarm);

            Slog.i(TAG, "Init Watchdog");
            Watchdog.getInstance().init(context, battery, power, alarm,
                    ActivityManagerService.self());

            Slog.i(TAG, "Window Manager");
            wm = WindowManagerService.main(context, power,
                    factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL,
                    !firstBoot, onlyCore);
            ServiceManager.addService(Context.WINDOW_SERVICE, wm);
            inputManager = wm.getInputManagerService();
            ServiceManager.addService(Context.INPUT_SERVICE, inputManager);

            ActivityManagerService.self().setWindowManager(wm);

            // Skip Bluetooth if we have an emulator kernel
            // TODO: Use a more reliable check to see if this product should
            // support Bluetooth - see bug 988521
            if (SystemProperties.get("ro.kernel.qemu").equals("1")) {
                Slog.i(TAG, "No Bluetooh Service (emulator)");
            } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
                Slog.i(TAG, "No Bluetooth Service (factory test)");
            } else {
                Slog.i(TAG, "Bluetooth Service");
                bluetooth = new BluetoothService(context);
                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);
                bluetooth.initAfterRegistration();

                if (!"0".equals(SystemProperties.get("system_init.startaudioservice"))) {
                    bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);
                    ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,
                                              bluetoothA2dp);
                    bluetooth.initAfterA2dpRegistration();
                }

                int bluetoothOn = Settings.Secure.getInt(mContentResolver,
                    Settings.Secure.BLUETOOTH_ON, 0);
                if (bluetoothOn != 0) {
                    bluetooth.enable();
                }
            }

        } catch (RuntimeException e) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting core service", e);
        }

        DevicePolicyManagerService devicePolicy = null;
        StatusBarManagerService statusBar = null;
        InputMethodManagerService imm = null;
        AppWidgetService appWidget = null;
        NotificationManagerService notification = null;
        WallpaperManagerService wallpaper = null;
        LocationManagerService location = null;
        CountryDetectorService countryDetector = null;
        TextServicesManagerService tsms = null;
        LockSettingsService lockSettings = null;
        DreamManagerService dreamy = null;
        //一下全是这些service 的创建
    }

在这里插入图片描述
最后来张图作为总结
我们到这里,大致看清了开启app的流程,但是后续还会有很多工作,我们下篇文章再续。

猜你喜欢

转载自blog.csdn.net/heimaer/article/details/84098739