Binder与Servicede关联

 

Binder是Android上IPC的基础和关键。那么在使用过程中,大多数时候看到的是client与server的结构,即Server通过创建服务来向Client提供服务,Client则通过绑定到Binder对象从而开始通信。

具体的binder对象的获取方式,也就与服务的调用方式相关了:
1.使用startService与指定service关联

 
  1. Intent intent =newIntent("com.example.bindser.JNIProxyService");
  2. startService(intent);

2.使用bindService与指定service关联

 
  1. Intent intent =newIntent("com.example.binderserver.JNIProxyService");
  2. bindService(intent, mConn, BIND_AUTO_CREATE);

3.直接获取指定系统服务的binder对象
如下时native中获取的方式,java类似。

 
  1. sp<IServiceManager> sm = defaultServiceManager();
  2. binder = sm->getService(String16("zp.svc"));
  3. Parcel data, reply;
  4. data.writeInt32(getpid());
  5. data.writeInt32(n);
  6. binder->transact(0, data,&reply);
  7. int r = reply.readInt32();

需要注意的是,上面这个例子针对的时native的service,如果service本身时java开发,则如上调用会失败,原因时通信过程中会遵循一个简单的协议,可以通过reverser analyze Java Interface.

参考
1. http://m.blog.csdn.net/blog/blackboyofsnp/7243070
2. http://m.blog.csdn.net/blog/longfeey/5887026

原文地址:https://www.cnblogs.com/rainduck/p/3917201.html