相信大家都知道威创,Service的啟動方式有兩種:startService和bindService丹泉,今天我們就一起從源碼的角度來學(xué)習(xí)下startService的啟動流程。
啟動一個(gè)Service的方式如下:
Intent intent = new Intent(MainActivity.this, TestService.class);
startService(intent);
我們跟進(jìn)去startService方法去看下:
#ContextWrapper
@Override
public ComponentName startService(Intent service) {
return mBase.startService(service);
}
可以看到滤祖,ContextWrapper中的startService方法直接調(diào)用到 mBase.startService碌更,mBase是什么呢?它又是在什么時(shí)候被賦值的呢尊剔?其實(shí)mBase就是 ContextImpl實(shí)例爪幻,了解過Activity啟動流程的朋友應(yīng)該很清楚,在Activity實(shí)例創(chuàng)建后须误,會調(diào)用到activity.attach方法挨稿,正是在這個(gè)方法中將當(dāng)前activity實(shí)例對應(yīng)的ContextImpl對象賦值給 mBase成員變量京痢。對Activity啟動流程還不熟悉的朋友可以看下筆者的 《Activity啟動流程源碼解析》:http://www.reibang.com/p/621ae18547b0奶甘;好了,我們接著跟進(jìn)去ContextImpl中的 startService方法:
#ContextImpl
@Override
public ComponentName startService(Intent service) {
warnIfCallingFromSystemProcess();
return startServiceCommon(service, false, mUser);
}
ContextImpl類中的startService方法中直接調(diào)用到 startServiceCommon方法:
private ComponentName startServiceCommon(Intent service, boolean requireForeground,
UserHandle user) {
try {
validateServiceIntent(service);
service.prepareToLeaveProcess(this);
//重點(diǎn)祭椰!
ComponentName cn = ActivityManager.getService().startService(
mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(
getContentResolver()), requireForeground,
getOpPackageName(), user.getIdentifier());
if (cn != null) {
if (cn.getPackageName().equals("!")) {
throw new SecurityException(
"Not allowed to start service " + service
+ " without permission " + cn.getClassName());
} else if (cn.getPackageName().equals("!!")) {
throw new SecurityException(
"Unable to start service " + service
+ ": " + cn.getClassName());
} else if (cn.getPackageName().equals("?")) {
throw new IllegalStateException(
"Not allowed to start service " + service + ": " + cn.getClassName());
}
}
return cn;
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
可以看到臭家,在 startServiceCommon方法中直接調(diào)用到 ActivityManager.getService().startService方法疲陕,和Activity的啟動流程一致,這里是由客戶端進(jìn)程向SystemServer進(jìn)程發(fā)起的一次單向IPC操作钉赁,最終調(diào)用到 ActivityManagerService類的startService方法蹄殃,我們跟進(jìn)去看下:
#ActivityManagerService
@Override
public ComponentName startService(IApplicationThread caller, Intent service,
String resolvedType, boolean requireForeground, String callingPackage, int userId)
throws TransactionTooLargeException {
enforceNotIsolatedCaller("startService");
// Refuse possible leaked file descriptors
if (service != null && service.hasFileDescriptors() == true) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}
if (callingPackage == null) {
throw new IllegalArgumentException("callingPackage cannot be null");
}
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
"*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground);
synchronized(this) {
final int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
ComponentName res;
try {
//重點(diǎn)!
res = mServices.startServiceLocked(caller, service,
resolvedType, callingPid, callingUid,
requireForeground, callingPackage, userId);
} finally {
Binder.restoreCallingIdentity(origId);
}
return res;
}
}
在ActivityManagerService的startService方法中橄霉,直接調(diào)用到 mServices.startServiceLocked方法窃爷,mServices對象的類型為ActiveServices,簡單來講姓蜂,ActiveServices是一個(gè)輔助AMS進(jìn)行Service管理的類按厘,包括Service的啟動、綁定和停止等钱慢。我們跟進(jìn)去mServices.startServiceLocked方法看下:
#ActiveServices
ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
throws TransactionTooLargeException {
...
//重點(diǎn)
ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
return cmp;
}
...
ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
ServiceState stracker = r.getTracker();
if (stracker != null) {
stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
}
r.callStart = false;
synchronized (r.stats.getBatteryStats()) {
r.stats.startRunningLocked();
}
//重點(diǎn)逮京!
String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
if (error != null) {
return new ComponentName("!!", error);
}
if (r.startRequested && addToStarting) {
boolean first = smap.mStartingBackground.size() == 0;
smap.mStartingBackground.add(r);
r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
if (DEBUG_DELAYED_SERVICE) {
RuntimeException here = new RuntimeException("here");
here.fillInStackTrace();
Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
} else if (DEBUG_DELAYED_STARTS) {
Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
}
if (first) {
smap.rescheduleDelayedStartsLocked();
}
} else if (callerFg || r.fgRequired) {
smap.ensureNotStartingBackgroundLocked(r);
}
return r.name;
}
...
private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
boolean whileRestarting, boolean permissionsReviewRequired)
throws TransactionTooLargeException {
...
if (app != null && app.thread != null) {
try {
app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
//重點(diǎn)!J懒棉!
realStartServiceLocked(r, app, execInFg);
return null;
} catch (TransactionTooLargeException e) {
throw e;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting service " + r.shortName, e);
}
// If a dead object exception was thrown -- fall through to
// restart the application.
}
...
}
可以看到最終是調(diào)用到 realStartServiceLocked方法,從名字上看览绿,這個(gè)方法應(yīng)該是真正啟動一個(gè)Service策严,我們跟進(jìn)去看下:
private final void realStartServiceLocked(ServiceRecord r,
ProcessRecord app, boolean execInFg) throws RemoteException {
...
//標(biāo)記當(dāng)前Service對象是否成功創(chuàng)建
boolean created = false;
try {
synchronized (r.stats.getBatteryStats()) {
r.stats.startLaunchedLocked();
}
mAm.notifyPackageUse(r.serviceInfo.packageName,
PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
//1.發(fā)起SystemServer進(jìn)程到客戶端進(jìn)程的單向IPC操作,創(chuàng)建Service對象并調(diào)用其onCreate方法
app.thread.scheduleCreateService(r, r.serviceInfo,
mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
app.repProcState);
r.postNotification();
created = true;
} catch (DeadObjectException e) {
Slog.w(TAG, "Application dead when creating service " + r);
mAm.appDiedLocked(app);
throw e;
} finally {
if (!created) {
// Keep the executeNesting count accurate.
final boolean inDestroying = mDestroyingServices.contains(r);
serviceDoneExecutingLocked(r, inDestroying, inDestroying);
// Cleanup.
if (newService) {
app.services.remove(r);
r.app = null;
}
// Retry.
if (!inDestroying) {
scheduleServiceRestartLocked(r, false);
}
}
}
if (r.whitelistManager) {
app.whitelistManager = true;
}
requestServiceBindingsLocked(r, execInFg);
updateServiceClientActivitiesLocked(app, null, true);
//2.同樣為IPC操作饿敲,最終調(diào)用到Service對象的onStartCommand方法
sendServiceArgsLocked(r, execInFg, true);
...
}
上述代碼重點(diǎn)部分已經(jīng)做了標(biāo)注妻导,我們首先來看下 1 處,可以看到 1 處調(diào)用到app.thread.scheduleCreateService方法怀各,由SystemServer進(jìn)程向客戶端進(jìn)程發(fā)起單向IPC操作倔韭,最終調(diào)用到 ApplicationThread 的scheduleCreateService方法,我們跟進(jìn)去看下:
public final void scheduleCreateService(IBinder token,
ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
updateProcessState(processState, false);
CreateServiceData s = new CreateServiceData();
s.token = token;
s.info = info;
s.compatInfo = compatInfo;
sendMessage(H.CREATE_SERVICE, s);
}
我們都知道ApplicationThread為SystemServer進(jìn)程到客戶端進(jìn)程單向通信對應(yīng)的Binder實(shí)現(xiàn)類瓢对,類中的方法都是運(yùn)行在客戶端的Binder線程池中寿酌,所以在scheduleCreateService方法的最后調(diào)用到sendMessage方法,由mH(Handler實(shí)例)發(fā)送了一條CREATE_SERVICE 類型的Message硕蛹,最終調(diào)用到 ActivityThread類的 handleCreateService方法醇疼,我們跟進(jìn)去看下:
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();
LoadedApk packageInfo = getPackageInfoNoCheck(
data.info.applicationInfo, data.compatInfo);
Service service = null;
try {
//1.通過類加載器創(chuàng)建Service實(shí)例
java.lang.ClassLoader cl = packageInfo.getClassLoader();
service = (Service) cl.loadClass(data.info.name).newInstance();
} catch (Exception e) {
if (!mInstrumentation.onException(service, e)) {
throw new RuntimeException(
"Unable to instantiate service " + data.info.name
+ ": " + e.toString(), e);
}
}
try {
if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
//2.創(chuàng)建ContextImpl實(shí)例
ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
context.setOuterContext(service);
//3.獲取到當(dāng)前Application實(shí)例
Application app = packageInfo.makeApplication(false, mInstrumentation);
//4.調(diào)用當(dāng)前Service對象的attach方法,進(jìn)行關(guān)聯(lián)操作
service.attach(context, this, data.info.name, data.token, app,
ActivityManager.getService());
//5.調(diào)用當(dāng)前Service對象的onCreate方法
service.onCreate();
//6.將當(dāng)前Service對象添加到mServices中
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);
}
}
}
可以看到在 handleCreateService方法中完成了Service對象的創(chuàng)建以及其 onCreate生命周期方法的調(diào)用妓美。
好了僵腺,我們回到 realStartServiceLocked方法的 2 處,繼續(xù)向下分析壶栋,可以看到 2 處調(diào)用到 sendServiceArgsLocked方法辰如,我們跟進(jìn)去看下:
#ActiveServices
private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
boolean oomAdjusted) throws TransactionTooLargeException {
...
try {
//重點(diǎn)
r.app.thread.scheduleServiceArgs(r, slice);
} catch (TransactionTooLargeException e) {
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
+ " args, first: " + args.get(0).args);
Slog.w(TAG, "Failed delivering service starts", e);
caughtException = e;
} catch (RemoteException e) {
// Remote process gone... we'll let the normal cleanup take care of this.
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
Slog.w(TAG, "Failed delivering service starts", e);
caughtException = e;
} catch (Exception e) {
Slog.w(TAG, "Unexpected exception", e);
caughtException = e;
}
...
}
在sendServiceArgsLocked方法中調(diào)用到 r.app.thread.scheduleServiceArgs方法,同樣為SystemServer進(jìn)程到應(yīng)用程序進(jìn)程的單向IPC操作贵试,最終調(diào)用到 ApplicationThread的scheduleServiceArgs方法琉兜,我們跟進(jìn)去看下:
#ApplicationThread
public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
List<ServiceStartArgs> list = args.getList();
for (int i = 0; i < list.size(); i++) {
ServiceStartArgs ssa = list.get(i);
ServiceArgsData s = new ServiceArgsData();
s.token = token;
s.taskRemoved = ssa.taskRemoved;
s.startId = ssa.startId;
s.flags = ssa.flags;
s.args = ssa.args;
sendMessage(H.SERVICE_ARGS, s);
}
}
我們可以看到凯正,scheduleServiceArgs方法中發(fā)送了一條 SERVICE_ARGS類型的Message,最終調(diào)用到 ActivityThread類的 handleServiceArgs方法豌蟋,我們跟進(jìn)去看下:
#ActivityThread
private void handleServiceArgs(ServiceArgsData data) {
//1.獲取到當(dāng)前Service對象
Service s = mServices.get(data.token);
if (s != null) {
try {
if (data.args != null) {
data.args.setExtrasClassLoader(s.getClassLoader());
data.args.prepareToEnterProcess();
}
int res;
if (!data.taskRemoved) {
//2.重點(diǎn)廊散,調(diào)用到當(dāng)前Service對象的 onStartCommand方法
res = s.onStartCommand(data.args, data.flags, data.startId);
} else {
s.onTaskRemoved(data.args);
res = Service.START_TASK_REMOVED_COMPLETE;
}
QueuedWork.waitToFinish();
try {
ActivityManager.getService().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
ensureJitEnabled();
} catch (Exception e) {
if (!mInstrumentation.onException(s, e)) {
throw new RuntimeException(
"Unable to start service " + s
+ " with " + data.args + ": " + e.toString(), e);
}
}
}
}
可以看到在 handleServiceArgs方法的 2 處調(diào)用到當(dāng)前 Service對象的 onStartCommand方法。
到這里梧疲,Service的啟動流程就分析完畢了允睹。