一、进程间通信的一个小事例
1、编写aidl文件
interface IUserAidl {
String getUserName();
String getPwd();
}
2、新建一个服务Service
public class UserService extends Service {
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private IUserAidl.Stub mBinder = new IUserAidl.Stub() {
@Override
public String getUserName() throws RemoteException {
return "dengzi";
}
@Override
public String getPwd() throws RemoteException {
return "servicepwd";
}
};
}
3、应用客户端调用
IUserAidl mAidl;
// 绑定Service
public void bindService(View view) {
Intent intent = new Intent(MainActivity.this, UserService.class);
bindService(intent, new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 连接成功
// 获取服务端返回的 Binder
mAidl = IUserAidl.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
// 连接失败
}
}, Context.BIND_AUTO_CREATE);
}
// 获取服务端的 getUserName()
public void getUserName(View view) {
try {
String userName = mAidl.getUserName();
Log.e("dengzi", "userName = " + userName);
} catch (RemoteException e) {
}
}
// 输出:
userName = dengzi
二、应用层的流程分析
我们先来看一下系统为我们自动生成的 IUserAidl 文件
public interface IUserAidl extends android.os.IInterface {
/**
* Stub 继承自Binder 实现了 IUserAidl ,连接后服务端返回的mBinder 也就是我们在
UserService 类中 new IUserAidl.Stub() 也就是客服端连接后的 IBinder service
*/
public static abstract class Stub extends android.os.Binder implements com.dengzi.pluginmain.IUserAidl {
private static final java.lang.String DESCRIPTOR = "com.dengzi.pluginmain.IUserAidl";
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* 这个方法是在客户端 onServiceConnected 中调用的返回是一个 Stub.Proxy
*/
public static com.dengzi.pluginmain.IUserAidl asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof com.dengzi.pluginmain.IUserAidl))) {
return ((com.dengzi.pluginmain.IUserAidl) iin);
}
return new com.dengzi.pluginmain.IUserAidl.Stub.Proxy(obj);
}
@Override
public android.os.IBinder asBinder() {
return this;
}
@Override
public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_getUserName: {
data.enforceInterface(DESCRIPTOR);
java.lang.String _result = this.getUserName();
reply.writeNoException();
// 服务端写数据 写入到reply里面
reply.writeString(_result);
return true;
}
case TRANSACTION_getPwd: {
data.enforceInterface(DESCRIPTOR);
java.lang.String _result = this.getPwd();
reply.writeNoException();
reply.writeString(_result);
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements com.dengzi.pluginmain.IUserAidl {
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) {
// 这是传递进来的服务端给我们返回的 IBinder其实也是Stub
mRemote = remote;
}
@Override
public android.os.IBinder asBinder() {
return mRemote;
}
public java.lang.String getInterfaceDescriptor() {
return DESCRIPTOR;
}
// 这个才是客户端获取用户名的实现方法
@Override
public java.lang.String getUserName() throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
java.lang.String _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
// 首先调用服务端返回的Ibinder实例调用transact方法写入到_reply中
mRemote.transact(Stub.TRANSACTION_getUserName, _data, _reply, 0);
_reply.readException();
// 然后进行读取
_result = _reply.readString();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public java.lang.String getPwd() throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
java.lang.String _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(Stub.TRANSACTION_getPwd, _data, _reply, 0);
_reply.readException();
_result = _reply.readString();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
}
static final int TRANSACTION_getUserName = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_getPwd = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
}
public java.lang.String getUserName() throws android.os.RemoteException;
public java.lang.String getPwd() throws android.os.RemoteException;
}
总结一下画一个流程图,客户端通过bindService连接服务端,会调用服务端Service的onBind方法返回一个IUserAidl.Stub的mBinder实例,然后将该实例返回给客户端的onServiceConnected()方法里面,有两个参数有一个IBinder就是服务端返回的mBinder,然后客户端通过该实例建立一个新的AIDL.Stub.Proxy对象,我们在客户端调用获取信息方法的时候其实就是调用的AIDL.Stub.Proxy里面的getUserName()方法,通过mBinder的onTransact()方法写入数据,然后获取数据,就这么个流程了。
image.png
二、源码分析:
目标 :
- 客户端调用bindService是怎么来到服务端service的onBind()方法?
- 服务端service是如何回调客户端的onServiceConnected()方法?
ContextImpl类中:
@Override
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
return bindServiceCommon(service, conn, flags, mMainThread.getHandler(),
Process.myUserHandle());
}
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, Handler
handler, UserHandle user) {
IServiceConnection sd;
if (mPackageInfo != null) {
// 将我们传入的 ServiceConnection 转为 IServiceConnection
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
} else {
}
validateServiceIntent(service);
try {
IBinder token = getActivityToken();
// 这里其实是调用 ActivityManagerService 的 bindService 方法
int res = ActivityManagerNative.getDefault().bindService(
mMainThread.getApplicationThread(), getActivityToken(), service,
service.resolveTypeIfNeeded(getContentResolver()),
sd, flags, getOpPackageName(), user.getIdentifier());
return res != 0;
} catch (RemoteException e) {
}
}
LoadedApk类中:
public final IServiceConnection getServiceDispatcher(ServiceConnection c,
Context context, Handler handler, int flags) {
synchronized (mServices) {
// ...
sd = new ServiceDispatcher(c, context, handler, flags);
return sd.getIServiceConnection();
}
}
static final class ServiceDispatcher {
private final ServiceDispatcher.InnerConnection mIServiceConnection;
ServiceDispatcher(ServiceConnection conn,
Context context, Handler activityThread, int flags) {
mIServiceConnection = new InnerConnection(this);
mConnection = conn;
// ...
}
IServiceConnection getIServiceConnection() {
return mIServiceConnection;
}
}
到这里我们知道: IServiceConnection 的实现类为 ServiceDispatcher.InnerConnection 类
来到ActivityManagerService 类中
public int bindService(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, IServiceConnection connection, int flags, String callingPackage,
int userId) throws TransactionTooLargeException {
enforceNotIsolatedCaller("bindService");
synchronized(this) {
return mServices.bindServiceLocked(caller, token, service,
resolvedType, connection, flags, callingPackage, userId);
}
}
ActiveServices类中
int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, final IServiceConnection connection, int flags,
String callingPackage, final int userId) throws TransactionTooLargeException {
// ...
bringUpServiceLocked(serviceRecord, serviceIntent.getFlags(), callerFg, false, false);
// ...
}
private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
boolean whileRestarting, boolean permissionsReviewRequired)
throws TransactionTooLargeException {
// ...
realStartServiceLocked(r, app, execInFg);
// ...
}
private final void realStartServiceLocked(ServiceRecord r,
ProcessRecord app, boolean execInFg) throws RemoteException {
// ...
requestServiceBindingsLocked(r, execInFg);
// ...
}
private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
throws TransactionTooLargeException {
for (int i=r.bindings.size()-1; i>=0; i--) {
IntentBindRecord ibr = r.bindings.valueAt(i);
if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
break;
}
}
}
private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
boolean execInFg, boolean rebind) throws TransactionTooLargeException {
// ...
r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
r.app.repProcState);
// ...
}
ActivityThread类中
public final void scheduleBindService(IBinder token, Intent intent,
boolean rebind, int processState) {
// ...
sendMessage(H.BIND_SERVICE, s);
}
case BIND_SERVICE:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
handleBindService((BindServiceData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
private void handleBindService(BindServiceData data) {
// 这个service就是服务端的service
Service s = mServices.get(data.token);
// 客户端bindService后一路到这里,终于调用了服务端的onBind方法
// 然后服务端将一个IBinder返回
IBinder binder = s.onBind(data.intent);
ActivityManagerNative.getDefault().publishService(
data.token, data.intent, binder);
}
来到ActivityManagerService 类中
public void publishService(IBinder token, Intent intent, IBinder service) {
synchronized(this) {
mServices.publishServiceLocked((ServiceRecord)token, intent, service);
}
}
ActiveServices类中
void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
final long origId = Binder.clearCallingIdentity();
try {
if (r != null) {
for (int conni = r.connections.size() - 1; conni >= 0; conni--) {
ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
for (int i = 0; i < clist.size(); i++) {
ConnectionRecord c = clist.get(i);
try {
// 这里以c.conn就是我们在前面找到的ServiceDispatcher.InnerConnection 类
c.conn.connected(r.name, service);
} catch (Exception e) {
}
}
}
}
} finally {
Binder.restoreCallingIdentity(origId);
}
}
LoadedApk类中:
private static class InnerConnection extends IServiceConnection.Stub {
final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;
InnerConnection(LoadedApk.ServiceDispatcher sd) {
mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);
}
public void connected(ComponentName name, IBinder service) throws RemoteException {
LoadedApk.ServiceDispatcher sd = mDispatcher.get();
if (sd != null) {
sd.connected(name, service);
}
}
}
public void connected(ComponentName name, IBinder service) {
if (mActivityThread != null) {
mActivityThread.post(new RunConnection(name, service, 0));
} else {
doConnected(name, service);
}
}
public void doConnected(ComponentName name, IBinder service) {
// ...
if (service != null) {
// 这里的mConnection就是我们传入的ServiceConnection
// 这里终于回调到了客户端的onServiceConnected方法,并把IBinder传回
mConnection.onServiceConnected(name, service);
}
}
网友评论