Android ActivityManagerService(AMS)的启动分析

Android中的AMS想必是做android开发的工程师耳熟能详的系统级别的服务,但是它又是如此地庞大(单单ActivityManagerService.java文件就2W+行代码),因此我们在学习它的时候总是不能找到实际的主线,很是混乱。这里我会连续写几篇文章从它的启动过程,主要业务逻辑,和别的模块之间的互操作逻辑等角度来向大家简单介绍一下它。这里我只能是抛砖引玉,简单介绍,不会面面俱到,因为AMS的代码量确实比较大,如果向大家一一道来,想必大家一定会厌烦而且学习效果不好。希望大家在阅读本文的时候,同时查看android相关源码,自己动手,自己思考,你会有很大的提高的!
注:本文的所有的分析全部基于google最新的android 6.0.0进行的,6.0之前的版本可能有很多地方不一致,请知悉。
好了下面,我们就开始从头分析一下AMS,首先从AMS的启动流程开始。

AMS的启动过程

Android中的很多使用java语言编写的service都是在SystemServer中启动的,SystemServer是由系统启动的时候zygote启动的第一个java程序。AMS的是在SystemServer中的startBootstrapServices方法中启动的,android系统中的很多核心关键服务都是在这个函数中启动的,这个方法中有这么一段代码:
startBootstrapServices@SystemServer.java:

// Activity manager runs the show.
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);

这里调用了mSystemServiceManager对象的startService启动了AMS,注意这里给出的参数是ActivityManagerService.Lifecycle.class,在进一步分析startService之前,我们需要看一下这个类:
Lifecycle@ActivityManagerService.java

public static final class Lifecycle extends SystemService {
    private final ActivityManagerService mService;

    public Lifecycle(Context context) {
        super(context);
        mService = new ActivityManagerService(context);
    }

    @Override
    public void onStart() {
        mService.start();
    }

    public ActivityManagerService getService() {
        return mService;
    }
}

从这个类的名字就可以看出来,这是一个关于AMS的生命周期的内部类,构造器中实例化了一个AMS的对象。同时这个类继承自SystemService类(这是所有系统级别服务都应该继承的父类,主要定义了一些关于生命周期和上下文的接口),并且复写了onStart方法:
onStart@SystemService.java

/** * Called when the dependencies listed in the @Service class-annotation are available * and after the chosen start phase. * When this method returns, the service should be published. */
public abstract void onStart();

可以看出来,这是当服务启动的时候回调的方法,具体再哪里调用,我们后面会分析。弄清楚了Lifecycle类之后,我们现在可以来分析mSystemServiceManager对象的startService方法,mSystemServiceManager是SystemServiceManager类的一个对象,下面是startService方法:
startService@SystemServiceManager.java

/** * Creates and starts a system service. The class must be a subclass of * {@link com.android.server.SystemService}. * * @param serviceClass A Java class that implements the SystemService interface. * @return The service instance, never null. * @throws RuntimeException if the service fails to start. */
@SuppressWarnings("unchecked")
public <T extends SystemService> T startService(Class<T> serviceClass) {
    final String name = serviceClass.getName();
    Slog.i(TAG, "Starting " + name);

    // Create the service.
    if (!SystemService.class.isAssignableFrom(serviceClass)) {
        throw new RuntimeException("Failed to create " + name
                + ": service must extend " + SystemService.class.getName());
    }
    final T service;
    try {
        Constructor<T> constructor = serviceClass.getConstructor(Context.class);
        service = constructor.newInstance(mContext);
    } catch (InstantiationException ex) {
        throw new RuntimeException("Failed to create service " + name
                + ": service could not be instantiated", ex);
    } catch (IllegalAccessException ex) {
        throw new RuntimeException("Failed to create service " + name
                + ": service must have a public constructor with a Context argument", ex);
    } catch (NoSuchMethodException ex) {
        throw new RuntimeException("Failed to create service " + name
                + ": service must have a public constructor with a Context argument", ex);
    } catch (InvocationTargetException ex) {
        throw new RuntimeException("Failed to create service " + name
                + ": service constructor threw an exception", ex);
    }

    // Register it.
    mServices.add(service);

    // Start it.
    try {
        service.onStart();
    } catch (RuntimeException ex) {
        throw new RuntimeException("Failed to start service " + name
                + ": onStart threw an exception", ex);
    }
    return service;
}

这里我们需要说明一下,在上面调用这个方法的时候,我们传递进来的参数是一个类,而不是这个类的对象,也就是说我们仅仅给出了类型并没有进行实例化!因此这里的方法参数是一个泛型。在这个方法中我们首先获得传递进来类的名字,然后进行一个很重要的操作,那就是java类型判断,使用isAssignableFrom完成,isAssignableFrom和instanceof类似,只是instanceof针对类的对象进行判断,而isAssignableFrom针对类进行判断,也就是说这是在只有类而没有类的对象的时候进行判断类之间的继承关系的方式。更多关于isAssignableFrom和instanceof的区别请看博客:
http://blog.csdn.net/kjfcpua/article/details/7045207
我们这里判断了传递进来的类是不是SystemService类的子类,如果不是的话直接刨除运行时异常立即停止运行,因为服务必须继承自SystemService类!代码中的异常信息也可以看到这一点。接下来,就获得类的构造器,并且实例化一个对象:

// 获得构造器
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
// 实例化一个对象
service = constructor.newInstance(mContext);

现在我们需要看一下实例化的时候做了什么工作,下面是Lifecycle类的构造器:

public Lifecycle(Context context) {
    super(context);
    mService = new ActivityManagerService(context);
}

我们可以看到,这里实例化了一个ActivityManagerService类的对象,我们看一下ActivityManagerService类的构造器:

// Note: This method is invoked on the main thread but may need to attach various
// handlers to other threads. So take care to be explicit about the looper.
public ActivityManagerService(Context systemContext) {
    mContext = systemContext;
    mFactoryTest = FactoryTest.getMode();
    // 获得当前运行在SystemServer中的ActivityThread对象
    mSystemThread = ActivityThread.currentActivityThread();

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

    // 创建用于处理本线程消息的线程和Handler对象,消息处理Handler是MainHandler类
    mHandlerThread = new ServiceThread(TAG,
            android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
    mHandlerThread.start();
    mHandler = new MainHandler(mHandlerThread.getLooper());
    mUiHandler = new UiHandler();

    // 创建intent广播管理类对象
    mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "foreground", BROADCAST_FG_TIMEOUT, false);
    mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "background", BROADCAST_BG_TIMEOUT, true);
    mBroadcastQueues[0] = mFgBroadcastQueue;
    mBroadcastQueues[1] = mBgBroadcastQueue;

    // 所有的service的列表对象
    mServices = new ActiveServices(this);
    // 所有的provider的列表对象
    mProviderMap = new ProviderMap(this);

    // TODO: Move creation of battery stats service outside of activity manager service.
    // 获得系统的/data/system目录,并且这个目录将用于创建MainHandler
    File dataDir = Environment.getDataDirectory();
    File systemDir = new File(dataDir, "system");
    systemDir.mkdirs();
    // 创建Battery服务对象
    mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
    mBatteryStatsService.getActiveStatistics().readLocked();
    mBatteryStatsService.scheduleWriteToDisk();
    mOnBattery = DEBUG_POWER ? true
            : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
    mBatteryStatsService.getActiveStatistics().setCallback(this);

    mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));

    mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"), mHandler);

// 打开/data/system/urigrants.xml,管理URI权限(与content provid读写有关)
// 更多关于URI权限可以查看: https://developer.android.com/guide/topics/security/permissions.html#uri
    mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));

    // User 0 is the first and only user that runs at boot.
    mStartedUsers.put(UserHandle.USER_OWNER, new UserState(UserHandle.OWNER, true));
    mUserLru.add(UserHandle.USER_OWNER);
    updateStartedUserArrayLocked();

    // 获得opengl es的版本信息
    GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
        ConfigurationInfo.GL_ES_VERSION_UNDEFINED);

    mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));

    mConfiguration.setToDefaults();
    mConfiguration.setLocale(Locale.getDefault());

    mConfigurationSeq = mConfiguration.seq = 1;
    mProcessCpuTracker.init();

    mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
    // 创建intent防火墙
    mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
    mRecentTasks = new RecentTasks(this);
    mStackSupervisor = new ActivityStackSupervisor(this, mRecentTasks);
    mTaskPersister = new TaskPersister(systemDir, mStackSupervisor, mRecentTasks);

    // cpu使用监控线程
    mProcessCpuThread = new Thread("CpuTracker") {
        @Override
        public void run() {
            while (true) {
                try {
                    try {
                        synchronized(this) {
                            final long now = SystemClock.uptimeMillis();
                            long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
                            long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
                            //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
                            // + ", write delay=" + nextWriteDelay);
                            if (nextWriteDelay < nextCpuDelay) {
                                nextCpuDelay = nextWriteDelay;
                            }
                            if (nextCpuDelay > 0) {
                                mProcessCpuMutexFree.set(true);
                                this.wait(nextCpuDelay);
                            }
                        }
                    } catch (InterruptedException e) {
                    }
                    updateCpuStatsNow();
                } catch (Exception e) {
                    Slog.e(TAG, "Unexpected exception collecting process stats", e);
                }
            }
        }
    };

    // 将服务加入看门狗的监控
    Watchdog.getInstance().addMonitor(this);
    Watchdog.getInstance().addThread(mHandler);
}

这个构造器比较长,并且基本都是一些AMS日常工作的初始化,包括创建四大组件的管理对象以及一些内部对象,因此我们这里就不详细分析构造器的工作了,后面分析AMS的服务逻辑的时候我们在来分析对应的初始化工作。这里有一点需要说一下,就是上面的创建intent防火墙部分,所谓intent防火墙是在android4.4.2中引入的一个intent过滤安全机制,在我们使用intent启动activity,service,发送广播的时候都会通过这个机制检查是不是允许执行,只有允许了才能真正执行。更多关于intent防火墙的介绍请看美国Syracuse University的一名研究生的文档(Google在这块基本没有文档,可能是方案还没有成熟。。。。):
http://www.cis.syr.edu/~wedu/android/IntentFirewall/index.html
现在我们只要知道在AMS的构造器中做了这些工作就可以了:
1. 创建一堆类的对象,这些对象对于AMS的日常工作来说是必需的。
2. 初始化battery stats相关服务,AMS除了负责activity的管理工作,还负责battery stats相关的工作
3. 初始化cpu统计相关服务,主要是启动一个线程,轮询处理。为AMS提供有关CPU运行统计方面数据做准备。
最后进行这个方法中最重要的操作,那就是将服务添加到ServiceManager中去,方面别的进程使用Binder查找到这个服务:

// Register it.
mServices.add(service);

需要注意的是,这里的添加注册服务并不是Binder添加注册服务,我们看一下mServices的类型就知道了:

// Services that should receive lifecycle events.
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();

是的,mServices就是一个列表,这个列表中包含了它启动的所有SystemService类的服务,以便于后面调用它的生命周期方法。
接下来的操作就是回调我们前面提到的onStart方法:

// Start it.
try {
    service.onStart();
} catch (RuntimeException ex) {
    throw new RuntimeException("Failed to start service " + name
            + ": onStart threw an exception", ex);
}

这里就回调到了AMS中Lifecycle内部类的onStart方法了,最后就是将实例化的service返回。接下来我们先分析一下Lifecycle的onStart:

@Override
public void onStart() {
    mService.start();
}

我们看到,这里直接调用ActivityManagerService的start方法:
start@ActivityManagerService.java

private void start() {
    Process.removeAllProcessGroups();
    mProcessCpuThread.start();

    mBatteryStatsService.publish(mContext);
    mAppOpsService.publish(mContext);
    Slog.d("AppOps", "AppOpsService published");
    LocalServices.addService(ActivityManagerInternal.class, new LocalService());
}

这里有的人可能觉得奇怪,怎么这个start是一个private方法?上面使用mService.start();能访问吗?是的,可以访问的,虽然它是一个私有方法!这里可以参考本人的另一篇文章:
http://blog.csdn.net/baniel01/article/details/51776120
这里的start方法很是简单,首先是调用Process类的removeAllProcessGroups方法移除所有的进程组,清空所有记录;然后就是启动ProcessCpuThread线程,mProcessCpuThread这个对象就是在刚才的构造器中初始化的;下面是发布BatteryStatsService,调用的是publish方法:
publish@BatteryStatsService.java

public void publish(Context context) {
    mContext = context;
    ServiceManager.addService(BatteryStats.SERVICE_NAME, asBinder());
    mStats.setNumSpeedSteps(new PowerProfile(mContext).getNumSpeedSteps());
    mStats.setRadioScanningTimeout(mContext.getResources().getInteger(
            com.android.internal.R.integer.config_radioScanningTimeout)
            * 1000L);
    mStats.setPowerProfile(new PowerProfile(context));
}

我们看到,这里首先就是将Battery stats服务注册到SM中去,然后就是设置一些运行时参数,具体这些参数是什么含义,读者可以自己分析一下BatteryStatsService的实现,这里我们就不详细分析了。
start方法的接下来的操作就是发布AppOpsService了,AppOpsService这个服务是提供android app ops服务的,什么是android app ops服务呢?App Ops是在android 4.3中加入的一个权限管理框架,这个框架可以让你自由地赋予或者撤销某个app的权限,方便管理,下图是操作时候的界面:
《Android ActivityManagerService(AMS)的启动分析》
关于android app ops,详见:
http://www.androidauthority.com/app-ops-need-know-324850/
下面是AppOpsService的publish方法:
publish@AppOpsService.java

public void publish(Context context) {
    mContext = context;
    ServiceManager.addService(Context.APP_OPS_SERVICE, asBinder());
}

我们看到,这里就更加简单了,直接就是向SM注册服务。
好了,如果读者还没有晕掉的话,你会知道上面我们都是在分析SystemServiceManager中的startService方法。。。。。(android的代码真是繁杂,长篇大论,真是烦人!)到目前为止,我们的分析流程是这样的:
1. tartBootstrapServices@SystemServer.java
2. startService@SystemServiceManager.java
3. Lifecycle@ActivityManagerService.java
4. onStart@Lifecycle
5. start@ActivityManagerService.java
现在我们回过头来看下startBootstrapServices@SystemServer.java中AMS的启动部分:

// Activity manager runs the show.
mActivityManagerService = mSystemServiceManager.startService(
        ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);

我们发现我们刚刚分析完了mSystemServiceManager.startService(ActivityManagerService.Lifecycle.class)这部分的逻辑!!在这方法调用完成之后会返回Lifecycle类的对象(上面讲解过,不知道你是不是记得??),然后调用这个对象的getService方法赋值给mActivityManagerService,getService方法定义如下:
getService@Lifecycle

public ActivityManagerService getService() {
    return mService;
}

而这里的mService就是在Lifecycle构造器中实例化的ActivityManagerService对象。
接下来在SystemServer.java中的操作就是调用AMS的setSystemServiceManager来将SystemServiceManager类的对象设置进去:
setSystemServiceManager@ActivityManagerService

public void setSystemServiceManager(SystemServiceManager mgr) {
   mSystemServiceManager = mgr;
}

这里就只是将对象保存下来,以后会使用到。SystemServiceManager是一个创建,启动,和管理其他有关SystemService类系统服务的管理类,我们从这个类的代码注释也能看到:
/**
* Manages creating, starting, and other lifecycle events of
* {@link com.android.server.SystemService system services}.
*
* {@hide}
*/
这里说的很清楚,并且这个类的方法也是简单明了,具体这个类在AMS中怎么使用,我们后面分析AMS的业务逻辑的时候会提到。在startBootstrapServices@SystemServer.java的最后就是调用setInstaller方法将installer设置进去。installer是用来安装app的,我们的AMS使用它只是想在AMS的启动完成的时候调用installer的markBootComplete方法告诉它现在AMS启动完成了,installer可以进行工作了。这个调用是在AMS的finishBooting方法中调用的,finishBooting是ActivityStackSupervisor中初始化完毕之后回调的,ActivityStackSupervisor是用来管理ActivityStack的,这个类是android 5.0中新引入的。这部分涉及到ActivityStack的管理,所以这里不过多涉及,后面我们分析ActivityStack实现时再来详述这部分。现在大家只要知道,AMS启动最后它的finishBooting会被ActivityStackSupervisor回调,然后这个方法中会调用installer的markBootComplete,并且还会调用SystemServiceManager的startBootPhase通知启动的阶段信息:
startBootPhase@SystemServiceManager.java

/** * Starts the specified boot phase for all system services that have been started up to * this point. * * @param phase The boot phase to start. */
public void startBootPhase(final int phase) {
    if (phase <= mCurrentPhase) {
        throw new IllegalArgumentException("Next phase must be larger than previous");
    }
    mCurrentPhase = phase;

    Slog.i(TAG, "Starting phase " + mCurrentPhase);

    final int serviceLen = mServices.size();
    for (int i = 0; i < serviceLen; i++) {
        final SystemService service = mServices.get(i);
        try {
            service.onBootPhase(mCurrentPhase);
        } catch (Exception ex) {
            throw new RuntimeException("Failed to boot service "
                    + service.getClass().getName()
                    + ": onBootPhase threw an exception during phase "
                    + mCurrentPhase, ex);
        }
    }
}

这部分代码比较简单,可以看到SystemServiceManager会从mServices列表中检出所有的service并且调用他们的onBootPhase方法通知启动的阶段信息。
到这里,AMS启动只是完成基本的准备阶段,下面还有很多的工作需要做的,大家有点耐心啊~~AMS作为android系统的重量级的服务,怎么会就那么简单呢??你说是吧?还是踏踏实实地看代码吧~~~~
接下的操作还是在startBootstrapServices方法中:
startBootstrapServices@SystemServer.java

// Now that the power manager has been started, let the activity manager
// initialize power management features.
mActivityManagerService.initPowerManagement();

这里的操作比较简单,注释中说道,既然power manager已经启动了,那么我们的AMS就可以初始化和battery stats相关的工作了。这里我们暂时先不详细分析initPowerManagement的过程,后面我们分析AMS的电源部分的时候会详细说明这一块的内容。接着往下看startBootstrapServices的中关于AMS的代码:

// Set up the Application instance for the system process and get started. mActivityManagerService.setSystemProcess();

这是startBootstrapServices中关于AMS的最后一个操作了,现在大家想一想,我们的AMS是一个Binder公共服务,每一个app都能通过getSystemService找到它的,但是到目前为止我们并没有看到任何关于在Binder中注册服务的逻辑啊?现在我们看一下setSystemProcess的实现:
setSystemProcess@ActivityManagerService.java

public void setSystemProcess() {
    try {
        ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
        ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
        ServiceManager.addService("meminfo", new MemBinder(this));
        ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
        ServiceManager.addService("dbinfo", new DbBinder(this));
        if (MONITOR_CPU_USAGE) {
            ServiceManager.addService("cpuinfo", new CpuBinder(this));
        }
        ServiceManager.addService("permission", new PermissionController(this));
        ServiceManager.addService("processinfo", new ProcessInfoService(this));

        ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                "android", STOCK_PM_FLAGS);
        mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

        synchronized (this) {
            ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
            app.persistent = true;
            app.pid = MY_PID;
            app.maxAdj = ProcessList.SYSTEM_ADJ;
            app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
            synchronized (mPidsSelfLocked) {
                mPidsSelfLocked.put(app.pid, app);
            }
            updateLruProcessLocked(app, false, null);
            updateOomAdjLocked();
        }
    } catch (PackageManager.NameNotFoundException e) {
        throw new RuntimeException(
                "Unable to find android system package", e);
    }
}

就是这里了,我们看到这个方法上来的第一句就是ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);这句话就是我们想要找的,这句话的意思就是通过Binder向系统服务大管家ServiceManager(SM)注册我们的服务,这样android中的其他进程就可以通过context的getSystemService找到我们的服务了。这个方法中的接下来的代码让我们感觉AMS挺不务正业的,它还分管着meminfo,gfxinfo,dbinfo,cpuinfo,permission,processinfo等业务,还真是忙啊!这里我们先不看这些业务,因为我们知道只有Activity的管理业务才是AMS的主页,其他的都只是副业而已了。
SystemServer在启动完成所有的服务之后,将调用AMS的systemReady()方法,这个方法是android系统进入用户交互阶段前最后进行的准备工作,这个方法比较长,我们分段分析一下它:
1). 如果现在已经启动完毕再次调用的话,就执行回调代码

public void systemReady(final Runnable goingCallback) {
synchronized(this) {
    if (mSystemReady) {
        // If we're done calling all the receivers, run the next "boot phase" passed in
        // by the SystemServer
        if (goingCallback != null) {
            goingCallback.run();
        }
        return;
    }

首先我们看到,这个方法中的全部代码都是处在保护区中的,也就是说必须保证线程间安全,刚开始我们的mSystemReady是false,所以这里的代码不会执行

mLocalDeviceIdleController
                    = LocalServices.getService(DeviceIdleController.LocalService.class);

这里是获得设备idle控制器,主要用于广播发送中的控制,后面我们分析广播机制的时候会提到这个内容。
2). 装载系统用户的profile id

// Make sure we have the current profile info, since it is needed for
// security checks.
updateCurrentProfileIdsLocked();

这部分代码是十分重要的,这里就是装载系统的用户ID的profile,用于后面的权限检查,这个是比较重要的信息,尤其是在android多用户的情况下,根据用户的ID配置赋予不同的权限。
3).重建recent task

mRecentTasks.clear();
mRecentTasks.addAll(mTaskPersister.restoreTasksLocked());
mRecentTasks.cleanupLocked(UserHandle.USER_ALL);
mTaskPersister.startPersisting();

这里是在android 5.0之后才有的部分,这部分的主要工作就是重建带有persistent标记的task。在android 5.0中支持带有persistent标记的task,这些task在系统关机的时候,系统会把它的信息保存在系统的/data/system/recent_tasks目录下的xml文件中,系统重启的时候通过这些文件会重新创建task。下面是我的机器中的/data/system/recent_tasks目录内容:
《Android ActivityManagerService(AMS)的启动分析》
我们随便打开一个文件看下内容:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<task task_id="13" real_activity="com.android.quicksearchbox/.SearchActivity" affinity="com.android.quicksearchbox" root_has_reset="true" auto_remove_recents="false" asked_compat_mode="false" user_id="0" effective_uid="10049" task_type="0" first_active_time="12804324289" last_active_time="12804367378" last_time_moved="12804324278" never_relinquish_identity="true" task_description_color="ffe6e6e6" task_affiliation_color="-1644826" task_affiliation="13" prev_affiliation="-1" next_affiliation="-1" calling_uid="10049" calling_package="com.android.quicksearchbox" resizeable="false" privileged="false">
        <intent action="android.search.action.GLOBAL_SEARCH" component="com.android.quicksearchbox/.SearchActivity" flags="14200000" />
</task>

这里记录的是android的google搜索框task的信息。
4). 广播升级更新的intent

// Check to see if there are any update receivers to run.
if (!mDidUpdate) {
    if (mWaitingUpdate) {
        return;
    }
    final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
    mWaitingUpdate = deliverPreBootCompleted(new Runnable() {
        public void run() {
            synchronized (ActivityManagerService.this) {
                mDidUpdate = true;
            }
            showBootMessage(mContext.getText(
                    R.string.android_upgrading_complete),
                    false);
            writeLastDonePreBootReceivers(doneReceivers);
            systemReady(goingCallback);
        }
    }, doneReceivers, UserHandle.USER_OWNER);

    if (mWaitingUpdate) {
        return;
    }
    mDidUpdate = true;
}

mAppOpsService.systemReady();
mSystemReady = true;

这里的代码就是用来处理android系统升级过程的,android系统升级的时候,系统的模块或者app也是需要开机的时候完成一些更新,例如重新整理数据等操作。这里我们调用了deliverPreBootCompleted方法发送了一个ACTION_PRE_BOOT_COMPLETED的消息通知这些模块。需要注意的是,这个消息只会发送给系统级别的app,并不会发送给第三方的app,具体的接受模块定义在/data/system/called_pre_boots.dat文件中,下面是我手机上的文件内容:

'6.0.1RELeng.baniel.20160128.114223com.android.providers.calendar6com.android.providers.calendar.CalendarUpgradeReceivercom.android.providers.contacts6com.android.providers.contacts.ContactsUpgradeReceivercom.android.managedprovisioning/com.android.managedprovisioning.PreBootListenercom.android.providers.media0com.android.providers.media.MediaUpgradeReceivercom.android.settings(com.android.settings.ManagedProfileSetup

可以看到这里都是一些系统级别的模块。
5). 清理多余进程,除了persistent进程


ArrayList<ProcessRecord> procsToKill = null;
synchronized(mPidsSelfLocked) {
    for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
        ProcessRecord proc = mPidsSelfLocked.valueAt(i);
        if (!isAllowedWhileBooting(proc.info)){
            if (procsToKill == null) {
                procsToKill = new ArrayList<ProcessRecord>();
            }
            procsToKill.add(proc);
        }
    }
}

synchronized(this) {
    if (procsToKill != null) {
        for (int i=procsToKill.size()-1; i>=0; i--) {
            ProcessRecord proc = procsToKill.get(i);
            Slog.i(TAG, "Removing system update proc: " + proc);
            removeProcessLocked(proc, true, false, "system update done");
        }
    }

    // Now that we have cleaned up any update processes, we
    // are ready to start launching real processes and know that
    // we won't trample on them any more.
    mProcessesReady = true;
}

这段代码的作用就是找到已经启动的应用进程,然后杀死他们,为什么呢?目的就是为了在home启动之前准备一个干净的环境。home启动之前的环境怎么会不干净呢?我们之前提到了,android系统会发送一个intent消息给系统模块,通知他们进行相应的升级,这里的这些模块就是有可能会在home运行之前运行的,为了不让这些模块的运行干扰我们home的正常逻辑,所以要就杀死他们。但是这里我们看到代码中定义了有一种进程是不会被杀死的,就是isAllowedWhileBooting返回true的进程,这个方法会检查进程是否带有FLAG_PERSISTENT标记,如果有的话就不用杀死他们,因为带有这个标识的进程下面我们还有启动他们的。

Slog.i(TAG, "System now ready");
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
    SystemClock.uptimeMillis());

这里就是打印event的log,没有什么逻辑。
6). 如果是工厂测试模式,则启动工厂测试模块


synchronized(this) {
    // Make sure we have no pre-ready processes sitting around.

    if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
        ResolveInfo ri = mContext.getPackageManager()
                .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
                        STOCK_PM_FLAGS);
        CharSequence errorMsg = null;
        if (ri != null) {
            ActivityInfo ai = ri.activityInfo;
            ApplicationInfo app = ai.applicationInfo;
            if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
                mTopAction = Intent.ACTION_FACTORY_TEST;
                mTopData = null;
                mTopComponent = new ComponentName(app.packageName,
                        ai.name);
            } else {
                errorMsg = mContext.getResources().getText(
                        com.android.internal.R.string.factorytest_not_system);
            }
        } else {
            errorMsg = mContext.getResources().getText(
                    com.android.internal.R.string.factorytest_no_action);
        }
        if (errorMsg != null) {
            mTopAction = null;
            mTopData = null;
            mTopComponent = null;
            Message msg = Message.obtain();
            msg.what = SHOW_FACTORY_ERROR_MSG;
            msg.getData().putCharSequence("msg", errorMsg);
            mUiHandler.sendMessage(msg);
        }
    }
}

这是判断如果当前系统处于“工厂测试模式”的话,就会启动用于工厂测试的模块。我们的手机在生产出厂的时候,都要进行工厂测试的,在工厂模式下运行的程序需要响应intent ACTION_FACTORY_TEST消息。这里主要就是查找响应该消息的程序,并且放在mTopComponent中,如果没有找到,就发送工场测试失败的消息。
7). 读取设置信息

        retrieveSettings();
        loadResourcesOnSystemReady();

这里调用retrieveSettings来读取设置,这个方法中的读取代码如下所示:

    private void retrieveSettings() {
        final ContentResolver resolver = mContext.getContentResolver();
        String debugApp = Settings.Global.getString(
            resolver, Settings.Global.DEBUG_APP);
        boolean waitForDebugger = Settings.Global.getInt(
            resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
        boolean alwaysFinishActivities = Settings.Global.getInt(
            resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
        boolean forceRtl = Settings.Global.getInt(
                resolver, Settings.Global.DEVELOPMENT_FORCE_RTL, 0) != 0;
        // Transfer any global setting for forcing RTL layout, into a System Property
        SystemProperties.set(Settings.Global.DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");

        Configuration configuration = new Configuration();
        Settings.System.getConfiguration(resolver, configuration);
        if (forceRtl) {
            // This will take care of setting the correct layout direction flags
            configuration.setLayoutDirection(configuration.locale);
        }

        synchronized (this) {
            mDebugApp = mOrigDebugApp = debugApp;
            mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
            mAlwaysFinishActivities = alwaysFinishActivities;
            // This happens before any activities are started, so we can
            // change mConfiguration in-place.
            updateConfigurationLocked(configuration, null, false, true);
            if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
                    "Initial config: " + mConfiguration);
        }
    }

我们看到,这里就读取一下4个设置:
DEBUG_APP:需要调试的app名称
WAIT_FOR_DEBUGGER:如果值为1,表示启动调试的app时需要先等待调试器,否则正常启动
ALWAYS_FINISH_ACTIVITIES:值为1的时候,表示activity已经不再需要,系统需要立即清理他们,这个可以在setting的开发者选项中设置。
DEVELOPMENT_FORCE_RTL:值为1表示要将系统设置为从右到左的模式(西亚地区部分语言,如希伯来语)。
接着systemReady的分析,在上面的方法之后调用了loadResourcesOnSystemReady方法从资源文件中读取了几个缺省的系统配置信息:

    /** Loads resources after the current configuration has been set. */
    private void loadResourcesOnSystemReady() {
        final Resources res = mContext.getResources();
        mHasRecents = res.getBoolean(com.android.internal.R.bool.config_hasRecents);
        mThumbnailWidth = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
        mThumbnailHeight = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
    }

继续看systemReady接下来的代码:
8).打开URI读取权限

        synchronized (this) {
            readGrantedUriPermissionsLocked();
        }

上面我们打开了URI权限的配置文件,这里我们就读取URI权限。
9).执行参数的callback,完成SystemServer的处理逻辑

if (goingCallback != null) goingCallback.run();

systemReady方法的参数就是一个Runnable对象,这里当这个对象不为空的时候,回调它的run方法,这个run方法主要执行SystemServer自己在这块的逻辑,主要就是一些后续的设置,准备,启动system ui,AMS开始观察本地程序的crash,和回调很多模块的systemReady和systemrunning方法。这个回调方法比较长,这里就不详细分析了。

Integer.toString(mCurrentUserId), mCurrentUserId);
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
Integer.toString(mCurrentUserId), mCurrentUserId);

这里通知BatteryStatsService当前用户启动消息(下面即将启动),BatteryStatsService会开始电池数据的统计分析。
10). 启动当前用户

 mSystemServiceManager.startUser(mCurrentUserId);

这里开始启动当前用户,为用户和系统交互做home桌面启动前的准备。
11).启动带有FLAG_PERSISTENT标记的应用,并且启动home launcher

 synchronized (this) {
  // 如果不是工厂测试模式
     if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
         try {
          // 查找带有persistent标记的app
             List apps = AppGlobals.getPackageManager().
                 getPersistentApplications(STOCK_PM_FLAGS);
             if (apps != null) {
                 int N = apps.size();
                 int i;
                 for (i=0; i<N; i++) {
                     ApplicationInfo info
                         = (ApplicationInfo)apps.get(i);
                     // 排除掉包名为“android”的app,因为前面已经加入过了。
                     if (info != null &&
                             !info.packageName.equals("android")) {
                         addAppLocked(info, false, null /* ABI override */);
                     }
                 }
             }
         } catch (RemoteException ex) {
             // pm is in same process, this will never happen.
         }
     }

     // Start up initial activity.
     mBooting = true;
     // 启动home桌面app
     startHomeActivityLocked(mCurrentUserId, "systemReady");

     try {
         if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
             Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
                     + " data partition or your device will be unstable.");
             mUiHandler.obtainMessage(SHOW_UID_ERROR_MSG).sendToTarget();
         }
     } catch (RemoteException e) {
     }

     if (!Build.isBuildConsistent()) {
         Slog.e(TAG, "Build fingerprint is not consistent, warning user");
         mUiHandler.obtainMessage(SHOW_FINGERPRINT_ERROR_MSG).sendToTarget();
     }

     long ident = Binder.clearCallingIdentity();
     try {
      // 发送用户启动完成的消息
         Intent intent = new Intent(Intent.ACTION_USER_STARTED);
         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
                 | Intent.FLAG_RECEIVER_FOREGROUND);
         intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
         broadcastIntentLocked(null, null, intent,
                 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
                 null, false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
         intent = new Intent(Intent.ACTION_USER_STARTING);
         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
         intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
         broadcastIntentLocked(null, null, intent,
                 null, new IIntentReceiver.Stub() {
                     @Override
                     public void performReceive(Intent intent, int resultCode, String data,
                             Bundle extras, boolean ordered, boolean sticky, int sendingUser)
                             throws RemoteException {
                     }
                 }, 0, null, null,
                 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
                 null, true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
     } catch (Throwable t) {
         Slog.wtf(TAG, "Failed sending first user broadcasts", t);
     } finally {
         Binder.restoreCallingIdentity(ident);
     }
     // 开始恢复显示activity栈顶的界面,也就是home的主界面。
     mStackSupervisor.resumeTopActivitiesLocked();
     sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
 }

这段代码的作用就是启动带有FLAG_PERSISTENT标记的app,启动应用通过调用addAppLocked方法完成,这个方法后面我们分析AMS的进程管理的时候再详细描述。接着就是启动我们熟悉的home了,通过调用startHomeActivityLocked方法完成,这个方法会首先查找当前home启动器,然后再启动对应的启动器(因为用户可能会下载安装了第三方的启动器)。home启动完成之后,系统会发送ACTION_BOOT_COMPLETE消息,通知app系统启动完成。
到这里,AMS的主体业务才算是启动完毕。这里我们简单分析了一下android中的AMS的在开机过程中的启动流程,目的就是给大家关于AMS启动的一个清晰的结构,并不是要面面俱到。个人感觉,android中的任何一个模块拿出来的话代码量都是巨大的,怎么从这些代码中找到android的设计的整体架构呢?最好的办法还是,先整体再模块,先抽象再具体。也就是先要知道整体的情况是什么样的,然后再研究细节部分,不然的话很有可能会深陷android代码泥沼,不能自拔……

    原文作者:createchance
    原文地址: https://blog.csdn.net/createchance/article/details/51777580
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞