最近碰到个问题,要从Java直接访问一个native service,这本来没有怎么问题,直接通过ServiceManager.getService获取IBinder即可,但是有个问题是这个native service是通过writeCString和readCString来获取字符串的,Java的Parcel中怎么也找不到对应的接口,最后还是通过Java的Parcel.writeInt来模拟writeCString解决了问题,代码如下:
IBinder service = ServiceManager.getService("helloService");
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
byte hello[] = "sayHello\0".getBytes("UTF8");
data.writeInterfaceToken("hello.service");
for (int i=0;i<hello.length/4*4;i+=4){
int n = 0;
for (int j=3;j>=0;j--) {
n = (n<<8) + Byte.valueOf(hello[i+j]).intValue();
}
data.writeInt(n);
}
int n = 0;
for (int i=hello.length-1;i>=hello.length/4*4;i--) {
n = (n<<8) + Byte.valueOf(hello[i]).intValue();
}
data.writeInt(n);
service.transact(SAY_HELLO, data, reply, 0);
int ret = reply.readInt();