Android输入法IMMS服务启动流程(1)(服务注册)
2019-10-22 本文已影响0人
古风子
前言
近期,在公司负责了安全键盘的需求,特意梳理了下Android 输入法相关的流程,以便对整个输入系统有一个整体的认识
基于Android 9.x
目录
1 SystemServer.startOtherServices
2 SystemServiceManager.startService
输入法服务注册过程
输入法服务启动和注册.pngSystemServer.startOtherServices
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
traceBeginAndSlog("StartInputMethodManagerLifecycle");
mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);
traceEnd();
}
传递的是InputMethodManagerService.Lifecycle.class;Lifecycle是一个SystemService对象
SystemServiceManager.startService
@SuppressWarnings("unchecked")
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
Slog.i(TAG, "Starting " + name);
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + 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 {
//初始化 new Lifecycle(mContext)
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);
}
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public void startService(@NonNull final SystemService service) {
// Register it.
//添加到本地ArrayList<SystemService>数组中
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
//调用Lifecycle的onStart方法
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
new Lifecycle
public Lifecycle(Context context) {
super(context);
mService = new InputMethodManagerService(context);
}
Lifecycle.onStart()
@Override
public void onStart() {
//注册本地服务,供system_server使用
LocalServices.addService(InputMethodManagerInternal.class,
new LocalServiceImpl(mService.mHandler));
//通过ServiceManager.addService注册服务,供应用层使用
publishBinderService(Context.INPUT_METHOD_SERVICE, mService);
}