«

ActivityManagerService 启动

时间:2024-3-2 17:14     作者:韩俊     分类: Html+Css


文章出处:http://blog.csdn.net/shift_wwx


前言:之前 android SystemServer详解 分析了一下systemserver的启动过程,虽然分析下来很多繁琐,可以systemserver却是android启动的第一步,很多service都是在这个进程中启动,这些才是组成android的关键,AMS可以说是android应用的最关键的一个service,传说中的android四大组件就是用它来控制的。我根据源码做一些分析,不足应该很多,希望大神能多指点。


1、AMS最开始涉及到是在systemserver中:

context = ActivityManagerService.main(factoryTest);
    public static final Context main(int factoryTest) {
        AThread thr = new AThread();//创建一个Looper,实例化AMS
        thr.start();

        synchronized (thr) {
            while (thr.mService == null) {//等待AMS实例化完成
                try {
                    thr.wait();
                } catch (InterruptedException e) {
                }
            }
        }

        ActivityManagerService m = thr.mService;//mSelf就是实例化的AMS
        mSelf = m;
        ActivityThread at = ActivityThread.systemMain();//实例化ActivityThread
        mSystemThread = at;
        Context context = at.getSystemContext();
        context.setTheme(android.R.style.Theme_Holo);
        m.mContext = context;
        m.mFactoryTest = factoryTest;
        m.mIntentFirewall = new IntentFirewall(m.new IntentFirewallInterface());

        m.mStackSupervisor = new ActivityStackSupervisor(m, context, thr.mLooper);//activity堆栈管理类

        m.mBatteryStatsService.publish(context);
        m.mUsageStatsService.publish(context);
        m.mAppOpsService.publish(context);

        synchronized (thr) {//mSelf初始化成功后,就可以让AThread中Looper loop起来
            thr.mReady = true;
            thr.notifyAll();
        }

        m.startRunning(null, null, null, null);//调用startRuuning

        return context;
    }
注意code中的注释。

1)AThread

    static class AThread extends Thread {
        ActivityManagerService mService;
        Looper mLooper;
        boolean mReady = false;

        public AThread() {
            super("ActivityManager");
        }

        @Override
        public void run() {
            Looper.prepare();

            android.os.Process.setThreadPriority(
                    android.os.Process.THREAD_PRIORITY_FOREGROUND);
            android.os.Process.setCanSelfBackground(false);

            ActivityManagerService m = new ActivityManagerService();

            synchronized (this) {
                mService = m;
                mLooper = Looper.myLooper();
                Watchdog.getInstance().addThread(new Handler(mLooper), getName());
                notifyAll();
            }

            synchronized (this) {
                while (!mReady) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                    }
                }
            }

            // For debug builds, log event loop stalls to dropbox for analysis.
            if (StrictMode.conditionallyEnableDebugLogging()) {
                Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
            }

            Looper.loop();
        }
    }

这个是AMS中的static class,为AMS创建了一个thread,区别去system_server进程的main thread,然后为AMS创建一个Looper,然后调用Looper.loop(); 另一个目的是实例化一个AMS。


private ActivityManagerService() {
        Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());

        mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT, false);
        mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT, true);
        mBroadcastQueues[0] = mFgBroadcastQueue;
        mBroadcastQueues[1] = mBgBroadcastQueue;

        mServices = new ActiveServices(this);
        mProviderMap = new ProviderMap(this);

        File dataDir = Environment.getDataDirectory();
        File systemDir = new File(dataDir, "system");
        systemDir.mkdirs();

        ......

}
构造函数就不详细的列出来,可以看一下AMS.java的source code。

一些变量需要注意,mBroadcastQueues(mFgBroadcastQueue、mBgBroadcastQueue)、mServices、mProviderMap四大组件三个在这里出现了,另外一个后期介绍。另外还有其他变量,mBatteryStatsService、mProcessStats、mUsageStatsService、mAppOpsService、mGrantFile、mStartedUsers、mCompatModePackages、mProcessCpuThread等等。

从code看,是在/data/system/下,创建了一些文件来管理android系统一些状态,例如batterystats.bin就是电池状态,接着procstats管理进程的,appops.xml就是app 权限相关的等等,后期会做详细的分析。


2)ActivityThread.systemMain()

    public static ActivityThread systemMain() {
        HardwareRenderer.disable(true);//初始化hardwareRenderer
        ActivityThread thread = new ActivityThread();//引入ResourceManager
        thread.attach(true);
        return thread;
    }

主要是ActivityThread.attach():

    private void attach(boolean system) {
        sCurrentActivityThread = this;
        mSystemThread = system;
        if (!system) {
            ViewRootImpl.addFirstDrawHandler(new Runnable() {
                @Override
                public void run() {
                    ensureJitEnabled();
                }
            });
            android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                    UserHandle.myUserId());
            RuntimeInit.setApplicationObject(mAppThread.asBinder());
            IActivityManager mgr = ActivityManagerNative.getDefault();
            try {
                mgr.attachApplication(mAppThread);
            } catch (RemoteException ex) {
                // Ignore
            }
        } else {
            // Don't set application object here -- if the system crashes,
            // we can't display an alert, we just want to die die die.
            android.ddm.DdmHandleAppName.setAppName("system_process",
                                                    UserHandle.myUserId());
            try {
                mInstrumentation = new Instrumentation();
                ContextImpl context = new ContextImpl();
                context.init(getSystemContext().mPackageInfo, null, this);
                Application app = Instrumentation.newApplication(Application.class, context);
                mAllApplications.add(app);
                mInitialApplication = app;
                app.onCreate();
            } catch (Exception e) {
                throw new RuntimeException(
                        "Unable to instantiate Application():" + e.toString(), e);
            }
        }

        // add dropbox logging to libcore
        DropBox.setReporter(new DropBoxReporter());

        ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
            @Override
            public void onConfigurationChanged(Configuration newConfig) {
                synchronized (mResourcesManager) {
                    // We need to apply this change to the resources
                    // immediately, because upon returning the view
                    // hierarchy will be informed about it.
                    if (mResourcesManager.applyConfigurationToResourcesLocked(newConfig, null)) {
                        // This actually changed the resources!  Tell
                        // everyone about it.
                        if (mPendingConfiguration == null ||
                                mPendingConfiguration.isOtherSeqNewer(newConfig)) {
                            mPendingConfiguration = newConfig;

                            sendMessage(H.CONFIGURATION_CHANGED, newConfig);
                        }
                    }
                }
            }
            @Override
            public void onLowMemory() {
            }
            @Override
            public void onTrimMemory(int level) {
            }
        });
    }
(1)android.ddm.DdmHandleAppName.setAppName("system_process", UserHandle.myUserId());
ddm是Dalvik Debug Monitor缩写,具体干嘛的不清楚,谁指点一下哦?

(2)Instrumentation类

(3)context

context第一次真正出现应该就是这里了:

ContextImpl context = new ContextImpl();
context.init(getSystemContext().mPackageInfo, null, this);










标签: javascript html css

热门推荐