Android Framework层Binder机制
2018-01-05 本文已影响64人
LeonXtp
Framework层Binder相关接口:
IInterface
接口:
public interface IInterface
{
/**
* Retrieve the Binder object associated with this interface.
* You must use this instead of a plain cast, so that proxy objects
* can return the correct result.
*/
public IBinder asBinder();
}
IBinder
接口:
public interface IBinder {
public String getInterfaceDescriptor() throws RemoteException;
public boolean pingBinder();
public boolean isBinderAlive();
public IInterface queryLocalInterface(String descriptor);
public void shellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
String[] args, ShellCallback shellCallback, ResultReceiver resultReceiver) throws RemoteException;
public interface DeathRecipient {
public void binderDied();
}
public void linkToDeath(DeathRecipient recipient, int flags)
throws RemoteException;
public boolean unlinkToDeath(DeathRecipient recipient, int flags);
}
AIDL简易示例:
aidl-example-structure.png
IMainInterface.aidl
代码:
package com.afollestad.aidlexample;
import com.afollestad.aidlexample.MainObject;
interface IMainService {
MainObject[] listFiles(String path);
void exit();
}
MainObject.aidl
代码:
package com.afollestad.aidlexample;
parcelable MainObject;
MainObject.java
代码:
public class MainObject implements Parcelable {
private String mPath;
public MainObject(Parcel source) {
mPath = source.readString();
}
public MainObject(String path) {
mPath = path;
}
public String getPath() {
return mPath;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mPath);
}
public static final Parcelable.Creator<MainObject> CREATOR = new Parcelable.Creator<MainObject>() {
@Override
public MainObject[] newArray(int size) {
return new MainObject[size];
}
@Override
public MainObject createFromParcel(Parcel source) {
return new MainObject(source);
}
};
}
MainService.java
代码:
public class MainService extends Service {
// 省略...
private final IMainService.Stub mBinder = new IMainService.Stub() {
@Override
public MainObject[] listFiles(String path) throws RemoteException {
log("Received list command for: " + path);
List<MainObject> toSend = new ArrayList<>();
// Generates a list of 1000 objects that aren't sent back to the binding Activity
for (int i = 0; i < 1000; i++) {
toSend.add(new MainObject("/example/item" + (i + 1)));
}
return toSend.toArray(new MainObject[toSend.size()]);
}
@Override
public void exit() throws RemoteException {
log("Received exit command.");
stopSelf();
}
};
}
编译之后,产生的aidl接口文件路径:
IMainService-build-path.png
其代码结构:
AIDL-build.png
IMainInterface.java
详细代码:
/*
* This file is auto-generated. DO NOT MODIFY.
* Original file: /home/bianjp/repos/android/hotfix/aidl-example/receiver/src/main/aidl/com/afollestad/aidlexample/IMainService.aidl
*/
package com.afollestad.aidlexample;
public interface IMainService extends android.os.IInterface {
/**
* Local-side IPC implementation stub class.
*/
public static abstract class Stub extends android.os.Binder implements com.afollestad.aidlexample.IMainService {
private static final java.lang.String DESCRIPTOR = "com.afollestad.aidlexample.IMainService";
/**
* Construct the stub at attach it to the interface.
*/
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an com.afollestad.aidlexample.IMainService interface,
* generating a proxy if needed.
*/
public static com.afollestad.aidlexample.IMainService asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof com.afollestad.aidlexample.IMainService))) {
return ((com.afollestad.aidlexample.IMainService) iin);
}
return new com.afollestad.aidlexample.IMainService.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_listFiles: {
data.enforceInterface(DESCRIPTOR);
java.lang.String _arg0;
_arg0 = data.readString();
com.afollestad.aidlexample.MainObject[] _result = this.listFiles(_arg0);
reply.writeNoException();
reply.writeTypedArray(_result, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
return true;
}
case TRANSACTION_exit: {
data.enforceInterface(DESCRIPTOR);
this.exit();
reply.writeNoException();
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements com.afollestad.aidlexample.IMainService {
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 com.afollestad.aidlexample.MainObject[] listFiles(java.lang.String path) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
com.afollestad.aidlexample.MainObject[] _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(path);
mRemote.transact(Stub.TRANSACTION_listFiles, _data, _reply, 0);
_reply.readException();
_result = _reply.createTypedArray(com.afollestad.aidlexample.MainObject.CREATOR);
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
@Override
public void exit() throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(Stub.TRANSACTION_exit, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
}
static final int TRANSACTION_listFiles = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_exit = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
}
public com.afollestad.aidlexample.MainObject[] listFiles(java.lang.String path) throws android.os.RemoteException;
public void exit() throws android.os.RemoteException;
}
附上一张Framework层Binder通信模型图:图片来源
app_binder_demo.jpg手写Binder示例
binder-framework-demo.png
IMyService.java
代码:
/**
* 作为接口
*/
public interface IMyService extends IInterface {
static final java.lang.String DESCRIPTOR = "com.yuanhh.frameworkBinder.MyServer";
public void sayHello(String str) throws RemoteException ;
static final int TRANSACTION_say = android.os.IBinder.FIRST_CALL_TRANSACTION;
}
MyServicce.java
代码:
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
public class MyService extends Binder implements IMyService{
public MyService() {
this.attachInterface(this, DESCRIPTOR);
}
@Override
public IBinder asBinder() {
return this;
}
/** 将MyService转换为IMyService接口 **/
public static com.yuanhh.frameworkBinder.IMyService asInterface(
android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iInterface = obj.queryLocalInterface(DESCRIPTOR);
if (((iInterface != null) && (iInterface instanceof com.yuanhh.frameworkBinder.IMyService))) {
return ((com.yuanhh.frameworkBinder.IMyService) iInterface);
}
return null;
}
/** 服务端,接收远程消息,处理onTransact方法 **/
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_say: {
data.enforceInterface(DESCRIPTOR);
String str = data.readString();
sayHello(str);
reply.writeNoException();
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
/** 自定义sayHello()方法 **/
@Override
public void sayHello(String str) {
System.out.println("MyService:: Hello, " + str);
}
}
ServiceProxy.java
代码:
import android.os.IBinder;
import android.os.RemoteException;
public class MyServiceProxy implements IMyService {
private android.os.IBinder mRemote; //´ú±íBpBinder
public MyServiceProxy(android.os.IBinder remote) {
mRemote = remote;
}
public java.lang.String getInterfaceDescriptor() {
return DESCRIPTOR;
}
@Override
public void sayHello(String str) throws RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeString(str);
mRemote.transact(TRANSACTION_say, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
@Override
public IBinder asBinder() {
return mRemote;
}
}
ServerDemo.java
:
import android.os.Looper;
import android.os.ServiceManager;
public class ServerDemo {
public static void main(String[] args) {
System.out.println("MyService Start");
Looper.prepareMainLooper(); //开启循环执行
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND); //设置为前台优先级
ServiceManager.addService("MyService", new MyService());//注册服务
Looper.loop();
}
}
ClientDemo.java
代码:
import android.os.IBinder;
import android.os.RemoteException;
import android.os.ServiceManager;
public class ClientDemo {
public static void main(String[] args) throws RemoteException {
System.out.println("Client start");
IBinder binder = ServiceManager.getService("MyService"); //获取名为"MyService"的服务
IMyService myService = new MyServiceProxy(binder); //创建MyServiceProxy对象
myService.sayHello("binder"); //通过MyServiceProxy对象调用接口的方法
System.out.println("Client end");
}
}