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 ? 
  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值