09-Binder通信机制完全解析
·
9. Binder通信机制完全解析 - 从Java到Native的完整链路
摘要
Binder是Android系统最重要的IPC机制,是Android Framework的基石。本文从AOSP源码层面深入剖析Binder的完整通信链路,包括Java层的Binder框架、Native层的实现、Binder驱动的工作原理、ServiceManager的作用、以及AIDL的本质。通过源码级分析和完整示例,帮助开发者彻底理解Binder从应用层到内核层的完整通信流程。
关键词:Binder、IPC、AIDL、ServiceManager、Binder驱动、跨进程通信、Parcel
1. Binder架构全景
1.1 Binder通信模型
1.2 Binder四大组件
| 组件 | 作用 | 位置 |
|---|---|---|
| Client | 客户端,发起远程调用 | 应用进程 |
| Server | 服务端,提供远程服务 | 应用进程/system_server |
| Binder Driver | 内核驱动,负责数据传输 | 内核空间 |
| ServiceManager | 服务注册中心 | servicemanager进程 |
2. Java层Binder框架
2.1 IBinder接口体系
// frameworks/base/core/java/android/os/IBinder.java
public interface IBinder {
/**
* 查询Binder接口描述符
*/
String getInterfaceDescriptor() throws RemoteException;
/**
* 检查Binder对象是否存活
*/
boolean pingBinder();
/**
* 检查Binder对象是否存活(阻塞版本)
*/
boolean isBinderAlive();
/**
* 查询Binder本地接口
*/
IInterface queryLocalInterface(String descriptor);
/**
* 核心方法:执行事务
* @param code 方法编号
* @param data 输入数据
* @param reply 输出数据
* @param flags 标志位(0=同步,FLAG_ONEWAY=异步)
*/
boolean transact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException;
/**
* 注册死亡通知
*/
void linkToDeath(DeathRecipient recipient, int flags)
throws RemoteException;
/**
* 取消死亡通知
*/
boolean unlinkToDeath(DeathRecipient recipient, int flags);
/**
* 死亡通知接口
*/
interface DeathRecipient {
void binderDied();
}
// 事务标志
int FLAG_ONEWAY = 0x00000001; // 单向调用,不等待返回
int FIRST_CALL_TRANSACTION = 0x00000001; // 用户事务起始值
int LAST_CALL_TRANSACTION = 0x00ffffff; // 用户事务结束值
// 系统事务
int PING_TRANSACTION = ('_'<<24)|('P'<<16)|('N'<<8)|'G';
int DUMP_TRANSACTION = ('_'<<24)|('D'<<16)|('M'<<8)|'P';
int INTERFACE_TRANSACTION = ('_'<<24)|('N'<<16)|('T'<<8)|'F';
// ...
}
2.2 Binder类(Native Binder的Java封装)
// frameworks/base/core/java/android/os/Binder.java
public class Binder implements IBinder {
private long mObject; // Native Binder对象指针
/**
* 获取调用者UID
*/
public static final native int getCallingUid();
/**
* 获取调用者PID
*/
public static final native int getCallingPid();
/**
* 清除调用者身份(返回原始身份token)
*/
public static final native long clearCallingIdentity();
/**
* 恢复调用者身份
*/
public static final native void restoreCallingIdentity(long token);
/**
* Flush pending Binder commands
*/
public static final native void flushPendingCommands();
/**
* 加入线程池
*/
public static final native void joinThreadPool();
/**
* 默认构造函数
*/
public Binder() {
mObject = getNativeBBinderHolder();
// ... 初始化
}
/**
* 实现IBinder.transact
*/
@Override
public final boolean transact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
// ... 权限检查等
boolean r;
try {
// 调用onTransact处理
r = onTransact(code, data, reply, flags);
} catch (RemoteException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (OutOfMemoryError e) {
throw e;
}
// ... 清理
return r;
}
/**
* 子类重写此方法处理事务
*/
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
if (code == INTERFACE_TRANSACTION) {
reply.writeString(getInterfaceDescriptor());
return true;
} else if (code == DUMP_TRANSACTION) {
ParcelFileDescriptor fd = data.readFileDescriptor();
String[] args = data.readStringArray();
if (fd != null) {
try {
dump(fd.getFileDescriptor(), args);
} finally {
IoUtils.closeQuietly(fd);
}
}
return true;
}
return false;
}
/**
* Attach to context
*/
public void attachInterface(IInterface owner, String descriptor) {
mOwner = owner;
mDescriptor = descriptor;
}
/**
* 查询本地接口
*/
@Override
public IInterface queryLocalInterface(String descriptor) {
if (mDescriptor != null && mDescriptor.equals(descriptor)) {
return mOwner;
}
return null;
}
// Native方法
private static native long getNativeBBinderHolder();
private native final void init();
private native final void destroy();
}
2.3 BinderProxy类(远程Binder的代理)
// frameworks/base/core/java/android/os/BinderProxy.java (简化)
final class BinderProxy implements IBinder {
private long mNativeData; // Native BBinder指针
/**
* 执行事务(Native实现)
*/
public native boolean transact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException;
/**
* 查询本地接口(始终返回null,因为是远程对象)
*/
public IInterface queryLocalInterface(String descriptor) {
return null;
}
/**
* 注册死亡通知
*/
public native void linkToDeath(DeathRecipient recipient, int flags)
throws RemoteException;
/**
* 取消死亡通知
*/
public native boolean unlinkToDeath(DeathRecipient recipient, int flags);
// ... 其他方法
/**
* 获取扩展信息
*/
public native IBinder getExtension() throws RemoteException;
}
3. AIDL原理与源码分析
3.1 AIDL接口定义
// IMyService.aidl
package com.example.binder;
interface IMyService {
// 基本类型
int add(int a, int b);
// String类型
String getData();
void setData(String data);
// Parcelable类型
User getUser(int uid);
void saveUser(in User user);
// List类型
List<User> getUserList();
// 单向调用(异步)
oneway void asyncCall(String message);
}
// User.aidl
package com.example.binder;
parcelable User;
// User.java
package com.example.binder;
public class User implements Parcelable {
public int uid;
public String name;
public int age;
public User() {}
public User(int uid, String name, int age) {
this.uid = uid;
this.name = name;
this.age = age;
}
protected User(Parcel in) {
uid = in.readInt();
name = in.readString();
age = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(uid);
dest.writeString(name);
dest.writeInt(age);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<User> CREATOR = new Creator<User>() {
@Override
public User createFromParcel(Parcel in) {
return new User(in);
}
@Override
public User[] newArray(int size) {
return new User[size];
}
};
}
3.2 AIDL生成的Java代码
// IMyService.java (AIDL编译器生成)
package com.example.binder;
public interface IMyService extends android.os.IInterface {
/**
* Stub - 服务端实现基类
*/
public static abstract class Stub extends android.os.Binder
implements com.example.binder.IMyService {
// 接口描述符
private static final java.lang.String DESCRIPTOR = "com.example.binder.IMyService";
/**
* 构造函数:将接口附加到Binder
*/
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* 将IBinder转换为IMyService接口
* 如果是本地Binder,返回本地对象;否则返回Proxy
*/
public static com.example.binder.IMyService asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof com.example.binder.IMyService))) {
return ((com.example.binder.IMyService) iin);
}
return new com.example.binder.IMyService.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 {
java.lang.String descriptor = DESCRIPTOR;
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(descriptor);
return true;
}
case TRANSACTION_add: {
data.enforceInterface(descriptor);
int _arg0 = data.readInt();
int _arg1 = data.readInt();
int _result = this.add(_arg0, _arg1);
reply.writeNoException();
reply.writeInt(_result);
return true;
}
case TRANSACTION_getData: {
data.enforceInterface(descriptor);
java.lang.String _result = this.getData();
reply.writeNoException();
reply.writeString(_result);
return true;
}
case TRANSACTION_setData: {
data.enforceInterface(descriptor);
java.lang.String _arg0 = data.readString();
this.setData(_arg0);
reply.writeNoException();
return true;
}
case TRANSACTION_getUser: {
data.enforceInterface(descriptor);
int _arg0 = data.readInt();
com.example.binder.User _result = this.getUser(_arg0);
reply.writeNoException();
if ((_result != null)) {
reply.writeInt(1);
_result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
} else {
reply.writeInt(0);
}
return true;
}
case TRANSACTION_saveUser: {
data.enforceInterface(descriptor);
com.example.binder.User _arg0;
if ((0 != data.readInt())) {
_arg0 = com.example.binder.User.CREATOR.createFromParcel(data);
} else {
_arg0 = null;
}
this.saveUser(_arg0);
reply.writeNoException();
return true;
}
case TRANSACTION_getUserList: {
data.enforceInterface(descriptor);
java.util.List<com.example.binder.User> _result = this.getUserList();
reply.writeNoException();
reply.writeTypedList(_result);
return true;
}
case TRANSACTION_asyncCall: {
data.enforceInterface(descriptor);
java.lang.String _arg0 = data.readString();
this.asyncCall(_arg0);
// oneway方法不写reply
return true;
}
default: {
return super.onTransact(code, data, reply, flags);
}
}
}
/**
* Proxy - 客户端代理
*/
private static class Proxy implements com.example.binder.IMyService {
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) {
mRemote = remote;
}
@Override
public android.os.IBinder asBinder() {
return mRemote;
}
public java.lang.String getInterfaceDescriptor() {
return DESCRIPTOR;
}
@Override
public int add(int a, int b) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(a);
_data.writeInt(b);
// 执行远程调用
boolean _status = mRemote.transact(Stub.TRANSACTION_add, _data, _reply, 0);
if (!_status && getDefaultImpl() != null) {
return getDefaultImpl().add(a, b);
}
_reply.readException();
_result = _reply.readInt();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public java.lang.String getData() 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);
boolean _status = mRemote.transact(Stub.TRANSACTION_getData, _data, _reply, 0);
if (!_status && getDefaultImpl() != null) {
return getDefaultImpl().getData();
}
_reply.readException();
_result = _reply.readString();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public void setData(java.lang.String data) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(data);
boolean _status = mRemote.transact(Stub.TRANSACTION_setData, _data, _reply, 0);
if (!_status && getDefaultImpl() != null) {
getDefaultImpl().setData(data);
return;
}
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
@Override
public com.example.binder.User getUser(int uid) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
com.example.binder.User _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(uid);
boolean _status = mRemote.transact(Stub.TRANSACTION_getUser, _data, _reply, 0);
if (!_status && getDefaultImpl() != null) {
return getDefaultImpl().getUser(uid);
}
_reply.readException();
if ((0 != _reply.readInt())) {
_result = com.example.binder.User.CREATOR.createFromParcel(_reply);
} else {
_result = null;
}
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public void saveUser(com.example.binder.User user) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
if ((user != null)) {
_data.writeInt(1);
user.writeToParcel(_data, 0);
} else {
_data.writeInt(0);
}
boolean _status = mRemote.transact(Stub.TRANSACTION_saveUser, _data, _reply, 0);
if (!_status && getDefaultImpl() != null) {
getDefaultImpl().saveUser(user);
return;
}
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
@Override
public java.util.List<com.example.binder.User> getUserList()
throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
java.util.List<com.example.binder.User> _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
boolean _status = mRemote.transact(Stub.TRANSACTION_getUserList, _data, _reply, 0);
if (!_status && getDefaultImpl() != null) {
return getDefaultImpl().getUserList();
}
_reply.readException();
_result = _reply.createTypedArrayList(com.example.binder.User.CREATOR);
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public void asyncCall(java.lang.String message) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(message);
// oneway调用,FLAG_ONEWAY
boolean _status = mRemote.transact(Stub.TRANSACTION_asyncCall, _data, null,
android.os.IBinder.FLAG_ONEWAY);
if (!_status && getDefaultImpl() != null) {
getDefaultImpl().asyncCall(message);
}
} finally {
_data.recycle();
}
}
// ... getDefaultImpl() 等方法
}
// 事务代码
static final int TRANSACTION_add = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_getData = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
static final int TRANSACTION_setData = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2);
static final int TRANSACTION_getUser = (android.os.IBinder.FIRST_CALL_TRANSACTION + 3);
static final int TRANSACTION_saveUser = (android.os.IBinder.FIRST_CALL_TRANSACTION + 4);
static final int TRANSACTION_getUserList = (android.os.IBinder.FIRST_CALL_TRANSACTION + 5);
static final int TRANSACTION_asyncCall = (android.os.IBinder.FIRST_CALL_TRANSACTION + 6);
}
// 接口方法声明
public int add(int a, int b) throws android.os.RemoteException;
public java.lang.String getData() throws android.os.RemoteException;
public void setData(java.lang.String data) throws android.os.RemoteException;
public com.example.binder.User getUser(int uid) throws android.os.RemoteException;
public void saveUser(com.example.binder.User user) throws android.os.RemoteException;
public java.util.List<com.example.binder.User> getUserList() throws android.os.RemoteException;
public void asyncCall(java.lang.String message) throws android.os.RemoteException;
}
3.3 AIDL服务端实现
/**
* AIDL服务端实现
*/
public class MyService extends Service {
private final IMyService.Stub mBinder = new IMyService.Stub() {
@Override
public int add(int a, int b) throws RemoteException {
Log.d("MyService", "add() called from UID: " + Binder.getCallingUid());
return a + b;
}
@Override
public String getData() throws RemoteException {
Log.d("MyService", "getData() called from PID: " + Binder.getCallingPid());
return "Data from server";
}
@Override
public void setData(String data) throws RemoteException {
Log.d("MyService", "setData(" + data + ") called");
// 保存数据
}
@Override
public User getUser(int uid) throws RemoteException {
Log.d("MyService", "getUser(" + uid + ") called");
return new User(uid, "User" + uid, 20 + uid);
}
@Override
public void saveUser(User user) throws RemoteException {
Log.d("MyService", "saveUser(" + user.name + ") called");
// 保存用户
}
@Override
public List<User> getUserList() throws RemoteException {
Log.d("MyService", "getUserList() called");
List<User> users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
users.add(new User(i, "User" + i, 20 + i));
}
return users;
}
@Override
public void asyncCall(String message) throws RemoteException {
Log.d("MyService", "asyncCall(" + message + ") called");
// 异步处理
new Thread(() -> {
// 耗时操作
try {
Thread.sleep(1000);
Log.d("MyService", "Async operation completed");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d("MyService", "onBind()");
return mBinder;
}
}
3.4 AIDL客户端调用
/**
* AIDL客户端调用
*/
public class MainActivity extends AppCompatActivity {
private IMyService mService;
private boolean mBound = false;
private final ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("MainActivity", "onServiceConnected");
// 将IBinder转换为IMyService接口
mService = IMyService.Stub.asInterface(service);
mBound = true;
// 注册死亡通知
try {
service.linkToDeath(mDeathRecipient, 0);
} catch (RemoteException e) {
e.printStackTrace();
}
// 调用远程方法
testRemoteCall();
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d("MainActivity", "onServiceDisconnected");
mService = null;
mBound = false;
}
};
private final IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
@Override
public void binderDied() {
Log.w("MainActivity", "Service died, reconnecting...");
if (mService != null) {
mService.asBinder().unlinkToDeath(this, 0);
mService = null;
}
// 重新绑定Service
bindRemoteService();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 绑定Service
bindRemoteService();
}
private void bindRemoteService() {
Intent intent = new Intent(this, MyService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
private void testRemoteCall() {
if (!mBound || mService == null) {
return;
}
try {
// 调用add方法
int result = mService.add(10, 20);
Log.d("MainActivity", "add(10, 20) = " + result);
// 调用getData方法
String data = mService.getData();
Log.d("MainActivity", "getData() = " + data);
// 调用setData方法
mService.setData("Hello from client");
// 调用getUser方法
User user = mService.getUser(100);
Log.d("MainActivity", "getUser(100) = " + user.name + ", age=" + user.age);
// 调用saveUser方法
User newUser = new User(200, "New User", 25);
mService.saveUser(newUser);
// 调用getUserList方法
List<User> users = mService.getUserList();
Log.d("MainActivity", "getUserList() size = " + users.size());
// 调用asyncCall方法(异步)
mService.asyncCall("Async message");
Log.d("MainActivity", "asyncCall() returned immediately");
} catch (RemoteException e) {
Log.e("MainActivity", "Remote exception", e);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mBound) {
// 取消死亡通知
if (mService != null) {
mService.asBinder().unlinkToDeath(mDeathRecipient, 0);
}
// 解绑Service
unbindService(mConnection);
mBound = false;
}
}
}
4. Native层Binder实现
4.1 Native Binder类体系
4.2 核心Native代码(简化)
// frameworks/native/libs/binder/include/binder/IBinder.h
class IBinder : public virtual RefBase {
public:
virtual status_t transact(uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0) = 0;
virtual status_t linkToDeath(const sp<DeathRecipient>& recipient,
void* cookie = nullptr,
uint32_t flags = 0) = 0;
virtual status_t unlinkToDeath(const wp<DeathRecipient>& recipient,
void* cookie = nullptr,
uint32_t flags = 0,
wp<DeathRecipient>* outRecipient = nullptr) = 0;
virtual BBinder* localBinder();
virtual BpBinder* remoteBinder();
class DeathRecipient : public virtual RefBase {
public:
virtual void binderDied(const wp<IBinder>& who) = 0;
};
};
// frameworks/native/libs/binder/Binder.cpp
class BBinder : public IBinder {
public:
virtual status_t transact(uint32_t code, const Parcel& data,
Parcel* reply, uint32_t flags = 0) {
// 调用onTransact
status_t err = onTransact(code, data, reply, flags);
if (reply != nullptr) {
reply->setDataPosition(0);
}
return err;
}
virtual status_t onTransact(uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags) {
switch (code) {
case PING_TRANSACTION:
return NO_ERROR;
case INTERFACE_TRANSACTION:
if (reply != nullptr) {
reply->writeString16(getInterfaceDescriptor());
}
return NO_ERROR;
default:
return UNKNOWN_TRANSACTION;
}
}
BBinder* localBinder() { return this; }
};
// frameworks/native/libs/binder/BpBinder.cpp
class BpBinder : public IBinder {
private:
const int32_t mHandle; // Binder句柄
public:
BpBinder(int32_t handle) : mHandle(handle) {}
virtual status_t transact(uint32_t code, const Parcel& data,
Parcel* reply, uint32_t flags = 0) {
// 通过Binder驱动发送数据
if (mHandle != 0) {
status_t status = IPCThreadState::self()->transact(
mHandle, code, data, reply, flags);
if (status == DEAD_OBJECT) {
// Binder已死亡
}
return status;
}
return DEAD_OBJECT;
}
BpBinder* remoteBinder() { return this; }
};
4.3 IPCThreadState - 线程IPC状态
// frameworks/native/libs/binder/IPCThreadState.cpp
class IPCThreadState {
public:
static IPCThreadState* self() {
// 线程本地存储
if (gHaveTLS) {
restart:
const pthread_key_t k = gTLS;
IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
if (st) return st;
return new IPCThreadState;
}
// ...
}
status_t transact(int32_t handle,
uint32_t code, const Parcel& data,
Parcel* reply, uint32_t flags) {
// 写入命令
err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, nullptr);
if ((flags & TF_ONE_WAY) == 0) {
// 等待回复
if (reply) {
err = waitForResponse(reply);
} else {
Parcel fakeReply;
err = waitForResponse(&fakeReply);
}
} else {
// oneway调用,不等待
err = waitForResponse(nullptr, nullptr);
}
return err;
}
private:
status_t writeTransactionData(int32_t cmd, uint32_t binderFlags,
int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer) {
binder_transaction_data tr;
tr.target.handle = handle;
tr.code = code;
tr.flags = binderFlags;
tr.cookie = 0;
tr.sender_pid = 0;
tr.sender_euid = 0;
const size_t dataSize = data.dataSize();
const size_t offsetsSize = data.objectsCount() * sizeof(binder_size_t);
tr.data_size = dataSize;
tr.offsets_size = offsetsSize;
tr.data.ptr.buffer = data.data();
tr.data.ptr.offsets = data.objects();
// 写入Binder驱动
mOut.writeInt32(cmd);
mOut.write(&tr, sizeof(tr));
return NO_ERROR;
}
status_t waitForResponse(Parcel *reply, status_t *acquireResult = nullptr) {
while (1) {
// 从Binder驱动读取
if ((err=talkWithDriver()) < NO_ERROR) break;
// 处理命令
err = executeCommand(cmd);
if (err != NO_ERROR) return err;
// 检查是否有回复
// ...
}
return err;
}
status_t talkWithDriver(bool doReceive) {
binder_write_read bwr;
// 设置读写缓冲区
bwr.write_size = mOut.dataSize();
bwr.write_buffer = (uintptr_t)mOut.data();
bwr.read_size = mIn.dataCapacity();
bwr.read_buffer = (uintptr_t)mIn.data();
// ioctl调用Binder驱动
if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0) {
err = NO_ERROR;
} else {
err = -errno;
}
return err;
}
};
5. ServiceManager原理
5.1 ServiceManager架构
5.2 注册与查询服务
/**
* 系统服务注册(Framework层)
*/
public class SystemServer {
private void startBootstrapServices() {
// 启动ActivityManagerService
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
// 注册到ServiceManager
ServiceManager.addService(Context.ACTIVITY_SERVICE, mActivityManagerService);
// 启动PackageManagerService
mPackageManagerService = PackageManagerService.main(...);
ServiceManager.addService("package", mPackageManagerService);
// ... 其他系统服务
}
}
/**
* 应用层获取系统服务
*/
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 获取ActivityManager
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
// 获取PackageManager
PackageManager pm = getPackageManager();
// 底层实现
// IBinder binder = ServiceManager.getService("activity");
// IActivityManager iam = IActivityManager.Stub.asInterface(binder);
}
}
6. 总结
6.1 Binder通信完整流程
6.2 核心要点
- Binder是C/S架构:Client通过Proxy调用,Server通过Stub响应
- 一次拷贝:数据从Client进程拷贝到内核,内核映射到Server进程
- ServiceManager:handle=0,所有服务注册中心
- AIDL本质:自动生成Proxy和Stub代码
- 线程池:Server端有Binder线程池处理请求
6.3 Binder优势
- 性能高:只需一次数据拷贝(vs Socket两次)
- 安全性好:内核添加UID/PID,防伪造
- 易用性强:面向对象的RPC调用
- 稳定性好:死亡通知机制
参考资源
本文基于 Android 13 (API 33) 源码分析
更多推荐


所有评论(0)