您的位置:首页 > 移动开发 > Android开发

Android服务之startService源码分析

2016-07-14 17:25 337 查看
先看下继承关系:



startService是Context的抽象方法,调用startService时,会先调用到ContextWrapper的startService方法:

@Override
public ComponentName startService(Intent service) {
return mBase.startService(service);
}


mBase是ContextImpl的实例,ContextWrapper类的startService方法最终通过ContextImpl类的startService方法来实现:

private ContextImpl(ContextImpl container, ActivityThread mainThread,
LoadedApk packageInfo, IBinder activityToken, UserHandle user, boolean restricted,
Display display, Configuration overrideConfiguration, int createDisplayWithId) {
...
// mUser和mMainThread是在构造方法里面赋的值
mUser = user;
mMainThread = mainThread;
...
}

@Override
public ComponentName startService(Intent service) {
warnIfCallingFromSystemProcess();
// mUser是UserHandle的实例,UserHandle实现了Parcelable接口
return startServiceCommon(service, mUser);
}

/**
* Logs a warning if the system process directly called a method such as
* {@link #startService(Intent)} instead of {@link #startServiceAsUser(Intent, UserHandle)}.
* The "AsUser" variants allow us to properly enforce the user's restrictions.
*/
private void warnIfCallingFromSystemProcess() {
// 如果是系统进程调用startService方法会打印一个log。
if (Process.myUid() == Process.SYSTEM_UID) {
Slog.w(TAG, "Calling a method in the system process without a qualified user: "
+ Debug.getCallers(5));
}
}

private ComponentName startServiceCommon(Intent service, UserHandle user) {
try {
// 验证intent的有效性
validateServiceIntent(service);
// 准备离开应用程序进程,进入ActivityManagerService进程(意味着bundle的数据要在进程间传递)
service.prepareToLeaveProcess();
// 调用ActivityManagerProxy类的startService来实现启动服务的操作
// ActivityManagerProxy是一个Binder对象的远程接口,而这个Binder对象就是ActivityManagerService。
ComponentName cn = ActivityManagerNative.getDefault().startService(
mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(
getContentResolver()), 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());
}
}
return cn;
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
}


一个进程对应一个ActivityThread实例,这个进程中所有的Activity对应这一个ActivityThread实例。

在ActivityThread类中,有一个成员变量mAppThread,它是一个ApplicationThread实例,它实现了IApplicationThread接口,它的作用是用来辅助ActivityThread执行一些操作。

mMainThread.getApplicationThread() 得到的是当前启动服务进程(调用者)的ApplicationThread对象

service.resolveTypeIfNeeded(getContentResolver()) 得到的是intent的MIME数据类型,它是在解析intent时用到的

getOpPackageName() 得到的是调用者的包名

private void validateServiceIntent(Intent service) {
// 隐式启动判断,5.1之后不允许隐式启动服务
if (service.getComponent() == null && service.getPackage() == null) {
if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
IllegalArgumentException ex = new IllegalArgumentException(
"Service Intent must be explicit: " + service);
throw ex;
} else {
Log.w(TAG, "Implicit intents with startService are not safe: " + service
+ " " + Debug.getCallers(2, 3));
}
}
}


ActivityManagerNative类中的getDefault方法通过单例模式创建ActivityManagerProxy代理对象。

实现继承关系:



ActivityManagerNative类:

/**
* Retrieve the system's default/global activity manager.
*/
static public IActivityManager getDefault() {
return gDefault.get();
}

private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
// 服务查询,返回BinderProxy对象
IBinder b = ServiceManager.getService("activity");
if (false) {
Log.v("ActivityManager", "default service binder = " + b);
}
// 创建与特定业务相关的代理对象
IActivityManager am = asInterface(b);
if (false) {
Log.v("ActivityManager", "default service = " + am);
}
return am;
}
};

/**
* Cast a Binder object into an activity manager interface, generating
* a proxy if needed.
*/
static public IActivityManager asInterface(IBinder obj) {
if (obj == null) {
return null;
}
// 如果之前已经创建过,则直接返回
IActivityManager in =
(IActivityManager)obj.queryLocalInterface(descriptor);
if (in != null) {
return in;
}

// 返回一个ActivityManagerProxy对象
return new ActivityManagerProxy(obj);
}


Singleton.java抽象类是用懒加载实现的,以后可以参考:

/**
* Singleton helper class for lazily initialization.
*
* @hide
*/
public abstract class Singleton<T> {
private T mInstance;

protected abstract T create();

public final T get() {
synchronized (this) {
if (mInstance == null) {
mInstance = create();
}
return mInstance;
}
}
}


ActivityManagerProxy类的startService方法把传递进来的参数写入到data本地变量中,接着通过mRemote.transact方法进入到Binder驱动程序,然后Binder驱动程序唤醒正在等待Client请求的ActivityManagerService进程,最后进入到ActivityManagerService的startService方法中,这里先看一下时序图:



public ActivityManagerService(Context systemContext) {
...
// mServices在构造方法中赋初值
mServices = new ActiveServices(this);
...
}

@Override
public ComponentName startService(IApplicationThread caller, Intent service,
String resolvedType, String callingPackage, int userId)
throws TransactionTooLargeException {
// 执行调用者不能是独立进程的判断
enforceNotIsolatedCaller("startService");
// Refuse possible leaked file descriptors
if (service != null && service.hasFileDescriptors() == true) {
// service中不能携带文件描述符
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);

/*可以在这里准备自启动的黑白名单初始化操作*/

synchronized(this) {
final int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
// 调用ActiveServices类的startServiceLocked方法
ComponentName res = mServices.startServiceLocked(caller, service,
resolvedType, callingPid, callingUid, callingPackage, userId);
Binder.restoreCallingIdentity(origId);
return res;
}
}

void enforceNotIsolatedCaller(String caller) {
// 根据uid判断该uid是不是独立的
if (UserHandle.isIsolated(Binder.getCallingUid())) {
throw new SecurityException("Isolated process not allowed to call " + caller);
}
}


执行到ActiveServices类中的startServiceLocked方法:

public ActiveServices(ActivityManagerService service) {
// 构造方法中给mAm赋初值
mAm = service;
...
}

ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
int callingPid, int callingUid, String callingPackage, int userId)
throws TransactionTooLargeException {
if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
+ " type=" + resolvedType + " args=" + service.getExtras());

final boolean callerFg;
if (caller != null) {
// 通过ApplicationThread对象从ActivityManagerService的成员变量mLruProcesses
// 列表中查找启动服务的进程(调用者)在ActivityManagerService中的ProcessRecord对象,
// 变量mLruProcesses的说明是:
/**
* List of running applications, sorted by recent usage.
* The first entry in the list is the least recently used.
*/
final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
if (callerApp == null) {
throw new SecurityException(
"Unable to find app for caller " + caller
+ " (pid=" + Binder.getCallingPid()
+ ") when starting service " + service);
}
callerFg = callerApp.setSchedGroup != Process.THREAD_GROUP_BG_NONINTERACTIVE;
} else {
callerFg = true;
}

// 调用retrieveServiceLocked方法解析service这个Intent,然后将解析结果放在res.record中。
// 调用该方法后,为被调用者构造了对应的ServiceRecord对象,并保存到ActivityManagerService的成员变量mServiceMap中。
ServiceLookupResult res =
retrieveServiceLocked(service, resolvedType, callingPackage,
callingPid, callingUid, userId, true, callerFg);
// 没有注册Service
if (res == null) {
return null;
}
if (res.record == null) {
return new ComponentName("!", res.permission != null
? res.permission : "private to package");
}

// caller是调用者,r是被调用者
ServiceRecord r = res.record;

if (!mAm.getUserManagerLocked().exists(r.userId)) {
Slog.d(TAG, "Trying to start service with non-existent user! " + r.userId);
return null;
}

/*可以添加关联唤醒的判断逻辑:如根据被调用者包名/类名前缀判断是否属于第三方push平台在开启服务,如果是则直接返回r.name*/

/*可以添加自启动的判断逻辑:如被调用者包名在禁止自启动的列表中,则直接返回r.name*/

// 权限检查
NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked(
callingUid, r.packageName, service, service.getFlags(), null, r.userId);
if (unscheduleServiceRestartLocked(r, callingUid, false)) {
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
}
// 初始化服务端的ServiceRecord信息
r.lastActivity = SystemClock.uptimeMillis();
r.startRequested = true;
r.delayedStop = false;
r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
service, neededGrants));

final ServiceMap smap = getServiceMap(r.userId);
boolean addToStarting = false;

// 判断是否需要延迟启动,需要则直接返回,不需要则addToStarting设为true
...

return startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
}


ActivityManagerService在请求Zygote进程孵化新的应用程序进程时,在ActivityManagerService服务端为每一个应用进程创建了对应的ProcessRecord对象来描述新的应用程序进程信息。startServiceLocked方法首先根据应用程序进程中的IApplicationThread对象在最近启动的应用程序列表mLruProcesses中为服务启动进程查找对应的ProcessRecord对象,如果启动Service的应用程序进程(调用者)还未启动,则抛异常。

然后调用retrieveServiceLocked方法为要启动的Service(被调用者)在ActivityManagerService服务端创建一个ServiceRecord对象来描述Service信息。

ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {

. . .
String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false);
if (error != null) {
return new ComponentName("!!", error);
}

. . .

return r.name;
}

private final String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
boolean whileRestarting) throws TransactionTooLargeException {

// 如果该Service已经创建,再次调用startService时,只调用该Service的onStartCommand来运行该Service
if (r.app != null && r.app.thread != null) {
// 启动Service
sendServiceArgsLocked(r, execInFg, false);
return null;
}

if (!whileRestarting && r.restartDelay > 0) {
// If waiting for a restart, then do nothing.
return null;
}

if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent);

// We are now bringing the service up, so no longer in the
// restarting state.
if (mRestartingServices.remove(r)) {
r.resetRestartCounter();
clearRestartingIfNeededLocked(r);
}

// Make sure this service is no longer considered delayed, we are starting it now.
if (r.delayed) {
if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
getServiceMap(r.userId).mDelayedStartList.remove(r);
r.delayed = false;
}

// Make sure that the user who owns this service is started.  If not,
// we don't want to allow it to run.
if (mAm.mStartedUsers.get(r.userId) == null) {
String msg = "Unable to launch app "
+ r.appInfo.packageName + "/"
+ r.appInfo.uid + " for service "
+ r.intent.getIntent() + ": user " + r.userId + " is stopped";
Slog.w(TAG, msg);
bringDownServiceLocked(r);
return msg;
}

// Service is now being launched, its package can't be stopped.
try {
AppGlobals.getPackageManager().setPackageStoppedState(
r.packageName, false, r.userId);
} catch (RemoteException e) {
} catch (IllegalArgumentException e) {
Slog.w(TAG, "Failed trying to unstop package "
+ r.packageName + ": " + e);
}

// 判断此Service是否在独立进程中启动
final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
// 得到的是在XML中设置该Service的进程名
final String procName = r.processName;
ProcessRecord app;

if (!isolated) {
// 根据进程名、uid从ActivityManagerService的成员变量mProcessNames中查找进程对应的描述符ProcessRecord
app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
+ " app=" + app);
if (app != null && app.thread != null) {
try {
app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
// 在现有的进程中启动Service
realStartServiceLocked(r, app, execInFg);
return null;
} catch (TransactionTooLargeException e) {
throw e;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting service " + r.shortName, e);
}
}
} else {
// If this service runs in an isolated process, then each time
// we call startProcessLocked() we will get a new isolated
// process, starting another process if we are currently waiting
// for a previous process to come up.  To deal with this, we store
// in the service any current isolated process it is running in or
// waiting to have come up.
app = r.isolatedProc;
}

// Not running -- get it started, and enqueue this service record
// to be executed when the app comes up.
if (app == null) {
// 创建一个新的进程
if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
"service", r.name, false, isolated, false)) == null) {
String msg = "Unable to launch app "
+ r.appInfo.packageName + "/"
+ r.appInfo.uid + " for service "
+ r.intent.getIntent() + ": process is bad";
Slog.w(TAG, msg);
// 如果启动失败则强制退出Service
bringDownServiceLocked(r);
return msg;
}
if (isolated) {
r.isolatedProc = app;
}
}

// mPendingServices用于保存客户进程请求启动的ServiceRecord
if (!mPendingServices.contains(r)) {
mPendingServices.add(r);
}

if (r.delayedStop) {
// Oh and hey we've already been asked to stop!
r.delayedStop = false;
if (r.startRequested) {
if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
"Applying delayed stop (in bring up): " + r);
stopServiceLocked(r);
}
}

return null;
}


根据上面代码的分析,第一次创建一个Service时的流程是:

1.创建进程:startProcessLocked

2.第一次启动Service:realStartServiceLocked

3.启动已有的Service:sendServiceArgsLocked

下面安装上面的流程讲解:

1.ActivityManagerService类中的startProcessLocked方法创建了一个进程,这里就不讲解源码了,有兴趣的可以看下。

2.ActiveServices类中的realStartServiceLocked方法:

private final void realStartServiceLocked(ServiceRecord r,
ProcessRecord app, boolean execInFg) throws RemoteException {
if (app.thread == null) {
throw new RemoteException();
}
if (DEBUG_MU)
Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
+ ", ProcessRecord.uid = " + app.uid);
r.app = app;
r.restartTime = r.lastActivity = SystemClock.uptimeMillis();

// 在ActivityManagerService服务中记录当前进程中运行的所有ServiceRecord
final boolean newService = app.services.add(r);
bumpServiceExecutingLocked(r, execInFg, "create");
// mLruProcesses保存系统最近运行的应用程序进程信息,更新当前ProcessRecord在mLruProcesses中的状态
mAm.updateLruProcessLocked(app, false, null);
mAm.updateOomAdjLocked();

boolean created = false;
try {
if (LOG_SERVICE_START_STOP) {
String nameTerm;
int lastPeriod = r.shortName.lastIndexOf('.');
nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
EventLogTags.writeAmCreateService(
r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
}
synchronized (r.stats.getBatteryStats()) {
r.stats.startLaunchedLocked();
}
// 检查当前Service所在的包是否经过DexOpt优化过
mAm.ensurePackageDexOpt(r.serviceInfo.packageName);
app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
// RPC调用ActivityThread类中的方法创建Service
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;
if (SERVICE_RESCHEDULE && DEBUG_DELAYED_SERVICE) {
Slog.w(TAG, " Failed to create Service !!!! ."
+"This will introduce huge delay...  "
+r.shortName + " in " + r.restartDelay + "ms");
}
}

// Retry.
if (!inDestroying) {
scheduleServiceRestartLocked(r, false);
}
}
}

// 绑定该Service
requestServiceBindingsLocked(r, execInFg);

updateServiceClientActivitiesLocked(app, null, true);

// If the service is in the started state, and there are no
// pending arguments, then fake up one so its onStartCommand() will
// be called.
if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
null, null));
}

// 启动该Service
sendServiceArgsLocked(r, execInFg, true);

if (r.delayed) {
if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
getServiceMap(r.userId).mDelayedStartList.remove(r);
r.delayed = false;
}

if (r.delayedStop) {
// Oh and hey we've already been asked to stop!
r.delayedStop = false;
if (r.startRequested) {
if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
"Applying delayed stop (from start): " + r);
stopServiceLocked(r);
}
}
}


上面方法完成了Service的创建、绑定、启动的调用。

真正的创建调用的是ActivityThread类中的scheduleCreateService方法:

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);
}


在上面方法中将调用参数信息封装为CreateServiceData对象,通过sendMessage方法向应用程序主线程MessageQueue中发送一个CREATE_SERVICE消息。

private class H extends Handler {

. . .
public static final int CREATE_SERVICE          = 114;
. . .

public void handleMessage(Message msg) {
switch (msg.what) {
. . .
case CREATE_SERVICE:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceCreate");
handleCreateService((CreateServiceData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
. . .
}
}
}


H是ActivityThread的内部类,这里又将Service的创建工作交给ActivityThread类的handleCreateService方法来完成:

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 {
java.lang.ClassLoader cl = packageInfo.getClassLoader();
// data.info.name就是Service是类名,通过类加载器根据类名创建一个实例后强转为Service类的实例
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);

ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
context.setOuterContext(service);

Application app = packageInfo.makeApplication(false, mInstrumentation);
service.attach(context, this, data.info.name, data.token, app,
ActivityManagerNative.getDefault());
// 回调Service的onCreate()方法
service.onCreate();
// mServices保存了应用程序进程中所有的Service,把Service添加到该变量中
mServices.put(data.token, service);
try {
// 通知ActivityManagerService,当前Service创建完成
ActivityManagerNative.getDefault().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
} catch (RemoteException e) {
// nothing to do.
}
} catch (Exception e) {
if (!mInstrumentation.onException(service, e)) {
throw new RuntimeException(
"Unable to create service " + data.info.name
+ ": " + e.toString(), e);
}
}
}


这样,Android系统创建服务的过程就分析完了。

3.ActiveServices类中的sendServiceArgsLocked方法:

private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
boolean oomAdjusted) throws TransactionTooLargeException {
final int N = r.pendingStarts.size();
if (N == 0) {
return;
}

// 遍历Service启动参数列表
while (r.pendingStarts.size() > 0) {
Exception caughtException = null;
ServiceRecord.StartItem si;
try {
// 对参数列表中的每一项StartItem都启动一次Service
si = r.pendingStarts.remove(0);
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Sending arguments to: "
+ r + " " + r.intent + " args=" + si.intent);
if (si.intent == null && N > 1) {
// If somehow we got a dummy null intent in the middle,
// then skip it.  DO NOT skip a null intent when it is
// the only one in the list -- this is to support the
// onStartCommand(null) case.
continue;
}
// 设置投递时间
si.deliveredTime = SystemClock.uptimeMillis();
// 将已投递参数项保存到deliveredStarts列表中
r.deliveredStarts.add(si);
si.deliveryCount++;
if (si.neededGrants != null) {
mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
si.getUriPermissionsLocked());
}
bumpServiceExecutingLocked(r, execInFg, "start");
if (!oomAdjusted) {
oomAdjusted = true;
mAm.updateOomAdjLocked(r.app);
}
int flags = 0;
if (si.deliveryCount > 1) {
flags |= Service.START_FLAG_RETRY;
}
if (si.doneExecutingCount > 0) {
flags |= Service.START_FLAG_REDELIVERY;
}
// RPC调用ActivityThread类中的方法启动Service
r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
} catch (TransactionTooLargeException e) {
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large: intent="
);
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);
caughtException = e;
} catch (Exception e) {
Slog.w(TAG, "Unexpected exception", e);
caughtException = e;
}

if (caughtException != null) {
// Keep nesting count correct
final boolean inDestroying = mDestroyingServices.contains(r);
serviceDoneExecutingLocked(r, inDestroying, inDestroying);
if (caughtException instanceof TransactionTooLargeException) {
throw (TransactionTooLargeException)caughtException;
}
break;
}
}
}


ActivityThread类中的scheduleServiceArgs方法:

public final void scheduleServiceArgs(IBinder token, boolean taskRemoved,
int startId, int flags, Intent args) {
ServiceArgsData s = new ServiceArgsData();
s.token = token;
s.taskRemoved = taskRemoved;
s.startId = startId;
s.flags = flags;
s.args = args;

sendMessage(H.SERVICE_ARGS, s);
}

private class H extends Handler {
. . .
public static final int SERVICE_ARGS            = 115;
. . .

public void handleMessage(Message msg) {
switch (msg.what) {
. . .
case SERVICE_ARGS:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStart");
handleServiceArgs((ServiceArgsData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
. . .
}
}

}


这里又将调用ActivityThread类的handleServiceArgs方法来启动服务:

private void handleServiceArgs(ServiceArgsData data) {
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) {
// 回调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 {
// 通知ActivityManagerService,Service启动完成
ActivityManagerNative.getDefault().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
} catch (RemoteException e) {
// nothing to do.
}
ensureJitEnabled();
} catch (Exception e) {
if (!mInstrumentation.onException(s, e)) {
throw new RuntimeException(
"Unable to start service " + s
+ " with " + data.args + ": " + e.toString(), e);
}
}
}
}


这样,Service的启动过程也分析完了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: