1.AMS的bindService
我们从调用bindService方法开始来看
bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE);
我们点击进入bindService方法,进入到了Context中的bindService中,而这个方法是一个抽象方法,而这个方法的具体实现其实是ContextWrapper中,所以我们直接看ContextWrapper的bindService方法
@Override
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
return mBase.bindService(service, conn, flags);
}
我们可以看到在ContextWrapper中的bindService又调用了mBase的bindService方法,mBase是Context类型,是一个抽象类,具体的实现类是ContextImpl,所以我们看ContextImpl中的bindService方法
@Override
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
warnIfCallingFromSystemProcess();
return bindServiceCommon(service, conn, flags, mMainThread.getHandler(),
Process.myUserHandle());
}
调用了bindServiceCommon方法
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, Handler
handler, UserHandle user) {
...
try {
...
int res = ActivityManager.getService().bindService(
mMainThread.getApplicationThread(), getActivityToken(), service,
service.resolveTypeIfNeeded(getContentResolver()),
sd, flags, getOpPackageName(), user.getIdentifier());
...
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
在这个方法中,我们清楚的看见调用了ActivityManager.getService方法,我们看下getService方法:
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
和Android7.0相比,这里有了明显的不同:Android7.0中,create方法中通过asInstance方法来获取IActivityManager对象的,并且可以进出查看asInstance方法,返回的对象为ActivityManagerProxy类;而这里的asInterface方法是IActivityManager.Stub持有的方法,并且查看不了,因为Android8.0之后使用了IActivityManager是使用AIDL进行生成的,细节被隐藏了。了解Android7.0的同学应该知道,这里实现的功能和Android7.0实现的功能是一样的,不了解的话可以先阅读我的上篇文章Android7.0 bindService源码解析_紫气东来_life的博客-CSDN博客
所以能,我们直接看AMS的bindService方法即可
2.Service的绑定过程
接着上面的,我们看AMS的bindService
public int bindService(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, IServiceConnection connection, int flags, String callingPackage,
int userId) throws TransactionTooLargeException {
...
synchronized(this) {
return mServices.bindServiceLocked(caller, token, service,
resolvedType, connection, flags, callingPackage, userId);
}
}
mService是ActiveServices,我们看ActiveServices的bindServiceLocked方法
int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, final IServiceConnection connection, int flags,
String callingPackage, final int userId) throws TransactionTooLargeException {
...
try {
....
if (s.app != null && b.intent.received) {
....
if (b.intent.apps.size() == 1 && b.intent.doRebind) {
requestServiceBindingLocked(s, b.intent, callerFg, true);
}
} else if (!b.intent.requested) {
requestServiceBindingLocked(s, b.intent, callerFg, false);
}
}
}
这里的代码很多,我阉割了无关的代码。调用requestServiceBindingLocked方法,并且第三个参数是为false,第三个参数是rebind,重新绑定的意思,我们看下代码
private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
boolean execInFg, boolean rebind) throws TransactionTooLargeException {
...
if ((!i.requested || rebind) && i.apps.size() > 0) {
try {
bumpServiceExecutingLocked(r, execInFg, "bind");
r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
r.app.repProcState);
if (!rebind) {
i.requested = true;
}
i.hasBound = true;
i.doRebind = false;
}
...
}
return true;
}
我们可以看到,调用了thread的scheduleBindService方法,这里thread其实就是ActivityThread,所以我们直接到ActivityThread中寻找scheduleBindService方法
public final void scheduleBindService(IBinder token, Intent intent,
boolean rebind, int processState) {
...
sendMessage(H.BIND_SERVICE, s);
}
sendMessage方法大家应该比较熟悉,所以直接找到接收H.BIND_SERVICE的地方就行了,同样是在ActivityThread方法中,如下:
case BIND_SERVICE:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
handleBindService((BindServiceData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
查看handleBindService方法
private void handleBindService(BindServiceData data) {
Service s = mServices.get(data.token);
if (s != null) {
try {
...
try {
if (!data.rebind) {
IBinder binder = s.onBind(data.intent);
ActivityManagerNative.getDefault().publishService(
data.token, data.intent, binder);
} else {
...
}
ensureJitEnabled();
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
} catch (Exception e) {
...
}
}
}
上面我们说了,ActivityManagerNative.getDefault是ActivityManagerProxy,所以我们直接看这个类的publishService方法
public void publishService(IBinder token,
Intent intent, IBinder service) throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
data.writeStrongBinder(token);
intent.writeToParcel(data, 0);
data.writeStrongBinder(service);
mRemote.transact(PUBLISH_SERVICE_TRANSACTION, data, reply, 0);
reply.readException();
data.recycle();
reply.recycle();
}
查看接收PUBLISH_SERVICE_TRANSACTION的地方,还是在ActivityManagerNative中
case PUBLISH_SERVICE_TRANSACTION: {
data.enforceInterface(IActivityManager.descriptor);
IBinder token = data.readStrongBinder();
Intent intent = Intent.CREATOR.createFromParcel(data);
IBinder service = data.readStrongBinder();
publishService(token, intent, service);
reply.writeNoException();
return true;
}
publishService的方法是在AMS中实现的,和之前的bindService是一样的,我们查看publishService方法
public void publishService(IBinder token, Intent intent, IBinder service) {
...
synchronized(this) {
....
mServices.publishServiceLocked((ServiceRecord)token, intent, service);
}
}
查看publishServiceLocked方法
void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
...
c.conn.connected(r.name, service);
...
}
关键的方法如上,这里的conn是IServiceConnection,而具体的实现类是LoadedApk.ServiceDispatcher,我们在ContextImpl的bindServiceCommon可以找到,如下
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, Handler
handler, UserHandle user) {
...
if (mPackageInfo != null) {
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
}
...
}
感兴趣的同学可以从这里去递进的查找,我这里就不贴代码了,最后会调用到LoadedApk.ServiceDispatcher的doConnected方法,如下:
public void doConnected(ComponentName name, IBinder service) {
...
// If there is a new service, it is now connected.
if (service != null) {
mConnection.onServiceConnected(name, service);
}
}
mConnection就是我们调用bindService时传入的ServiceConnection,绑定成功后,从这里回调
bindService到此结束了