LocalServices和SystemService等简介

Android 91es.com站长2023年8月19日 am8:08发布10个月前更新
0
导航号,我的单页导航
目录

前言

在上次简单介绍SystemServer(《SystenServer的启动之一》)时,里面涉及几个比较重要的类SystemServiceManagerSystemServiceLocalServices,因此今天就单独介绍一下。

正文

涉及文件

frameworks\base\services\java\com\android\server\SystemServer.java
frameworks\base\services\core\java\com\android\server\SystemService.java
frameworks\base\services\core\java\com\android\server\SystemServiceManager.java
frameworks\base\core\java\com\android\server\LocalServices.java
frameworks\base\services\core\java\com\android\server\lights\LightsService.java

SystemService.java

虽然名字带有Service,并不是真正的Service,只是一个抽象类,定义了些[系统服务]共同的方法和属性。

这个主要是让系[统服务]]继承这个类。

比如

//Installer.java
public class Installer extends SystemService {
}
//PowerManagerService.java
public final class PowerManagerService extends SystemService
        implements Watchdog.Monitor {
}
//LightsService.java
public class LightsService extends SystemService {
}

SystemServiceManager.java

mSystemServiceManager = new SystemServiceManager(mSystemContext);

这个mSystemServiceManager在SystemServer中很常见,主要功能:

  1. 启动[系统服务]

  2. 通知[系统服务]更新Boot Phase

  3. 通知[系统服务]切换用户

SystemServiceManager中存在mServices列表,用于存储启动过的[系统服务]。

private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
启动[系统服务]

这块之前在《SystenServer的启动之一》介绍过。

startService()
public SystemService startService(String className) {
    final Class<SystemService> serviceClass;
    try {
        //返回className类对象,如果无法加载就会异常。
        serviceClass = (Class<SystemService>)Class.forName(className);
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException("Failed to create service " + className
                + ": service class not found, usually indicates that the caller should "
                + "have called PackageManager.hasSystemFeature() to check whether the "
                + "feature is available on this device before trying to start the "
                + "services that implement it", ex);
    }
    return startService(serviceClass);
}

接着的startService()主要作用:

  1. 判断serviceClass是否继承SystemService

  2. 获取构造函数初始化Service

  3. 启动服务的startService()

@SuppressWarnings("unchecked")
public <T extends SystemService> T startService(Class<T> serviceClass) {
    try {
        final String name = serviceClass.getName();
        //判断serviceClass继承于SystemService
        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对象初始化
         service = constructor.newInstance(mContext);
        } catch (InstantiationException ex) {
            throw new RuntimeException("Failed to create service " + name
                    + ": service could not be instantiated", ex);
        }
        startService(service);
        return service;//返回创建的服务对象
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
}
  1. 添加创建的service到mServices列表中,方便后续获取和查询

  2. 调用服务中的onStart()

public void startService(@NonNull final SystemService service) {
    //添加到服务列表,后面可以通过getService获取服务。
    mServices.add(service);
    try {
        //调用服务中的onStart()
        service.onStart();
    } catch (RuntimeException ex) {
        throw new RuntimeException("Failed to start service " + service.getClass().getName()
                + ": onStart threw an exception", ex);
    }
}

哈哈,从上面看,[系统服务]也就是模拟服务启动而已。完全可以看做创建了一个类对象并执行了onStart()。

更新Phase状态
public void startBootPhase(final int phase) {
    //mCurrentPhase默认-1
    if (phase <= mCurrentPhase) {
        throw new IllegalArgumentException("Next phase must be larger than previous");
    }
    //更新mCurrentPhase
    mCurrentPhase = phase;
    try {
        final int serviceLen = mServices.size();
        //有新phase状态,通知所有启动了的[系统服务]
        for (int i = 0; i < serviceLen; i++) {
            final SystemService service = mServices.get(i);
            long time = SystemClock.elapsedRealtime();
            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);
            }
        }
    } finally {
    }
}
切换用户

至于切换用户,这里涉及如下几个方法

  1. startUser()

  2. unlockUser()

  3. switchUser()

  4. stopUser()

  5. cleanupUser()

Android是支持多用户的,也就是每个用户的配置信息不一样,因此每次变化都需要通知所有[系统服务]进行切换对用的配置。

LocalServices.java

LocalServices类也很简单,也就是用map存储[服务],然后提供添加,查询和删除功能。

存在的不一定是服务哈!

public final class LocalServices {
    private LocalServices() {}
    //用键值对存储服务
    private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =
            new ArrayMap<Class<?>, Object>();
    //通过key进行查询服务
    @SuppressWarnings("unchecked")
    public static <T> T getService(Class<T> type) {
        synchronized (sLocalServiceObjects) {
            return (T) sLocalServiceObjects.get(type);
        }
    }
    //通过key添加服务
    public static <T> void addService(Class<T> type, T service) {
        synchronized (sLocalServiceObjects) {
            if (sLocalServiceObjects.containsKey(type)) {
                throw new IllegalStateException("Overriding service registration");
            }
            sLocalServiceObjects.put(type, service);
        }
    }
    //通过key进行移除服务
    @VisibleForTesting
    public static <T> void removeServiceForTest(Class<T> type) {
        synchronized (sLocalServiceObjects) {
            sLocalServiceObjects.remove(type);
        }
    }
}

这个也在代码中很常用

SystemServer.run()
# 存储mSystemServiceManager
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
LightsService.onStart()
@Override
public void onStart() {
    publishLocalService(LightsManager.class, mService);
}
protected final <T> void publishLocalService(Class<T> type, T service) {
    LocalServices.addService(type, service);
}

这里添加的是LightsManager对象。

参考文章

  1. SystenServer的启动之一

版权声明 1、 本站名称 91易搜
2、 本站网址 https://www.91es.com/
3、 本站部分文章来源于网络,仅供学习与参考,如有侵权请留言
4、 本站禁止发布或转载任何违法的相关信息,如有发现请向站长举报
导航号,我的单页导航

暂无评论

评论审核已启用。您的评论可能需要一段时间后才能被显示。

暂无评论...