ActivityThread的handleCreateService方法用于处理ServiceCreate请求,代码如下:
//frameworks/base/core/java/android/app/ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler implements ActivityThreadInternal {
final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
private void handleCreateService(CreateServiceData data) {
// If we are getting ready to gc after going to the background, well
// we are back active so skip it.
unscheduleGcIdler();
// 获取启动Service的应用程序的LoadedApk,LoadedApk是一个APK文件的描述类
LoadedApk packageInfo = getPackageInfoNoCheck(
data.info.applicationInfo, data.compatInfo);
Service service = null;
try {
if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
Application app = packageInfo.makeApplicationInner(false, mInstrumentation);
final java.lang.ClassLoader cl;
if (data.info.splitName != null) {
// 获取类加载器
cl = packageInfo.getSplitClassLoader(data.info.splitName);
} else {
// 加载Service类
cl = packageInfo.getClassLoader();
}
service = packageInfo.getAppFactory()
.instantiateService(cl, data.info.name, data.intent); //实例化Service
// 通过ContextImpl的createAppContext方法创建ContextImpl也就是Service的上下文
ContextImpl context = ContextImpl.getImpl(service
.createServiceBaseContext(this, packageInfo));
if (data.info.splitName != null) {
context = (ContextImpl) context.createContextForSplit(data.info.splitName);
}
if (data.info.attributionTags != null && data.info.attributionTags.length > 0) {
final String attributionTag = data.info.attributionTags[0];
context = (ContextImpl) context.createAttributionContext(attributionTag);
}
// Service resources must be initialized with the same loaders as the application
// context.
// 必须使用与应用程序上下文相同的加载程序初始化服务资源。
context.getResources().addLoaders(
app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
context.setOuterContext(service);
service.attach(context, this, data.info.name, data.token, app,
ActivityManager.getService()); //将ContextImpl传入service的attach方法中
service.onCreate(); // 调用 service的 onCreate()方法
mServicesData.put(data.token, data);
mServices.put(data.token, service);
try {
ActivityManager.getService().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
} catch (Exception e) {
if (!mInstrumentation.onException(service, e)) {
throw new RuntimeException(
"Unable to create service " + data.info.name
+ ": " + e.toString(), e);
}
}
}
}
上面方法主要处理如下:
1、加载Service类。
2、实例化Service。
3、调用Service的attach方法。
4、调用Service的onCreate方法。
下面分别进行分析:
Service attach
调用Service的attach方法:
Android13 Service attach流程分析-CSDN博客
Service onCreate
调用Service的onCreate方法:
void onCreate():服务第一次创建时由系统调用。