参考文献:
http://blog.csdn.net/baiyanning/article/details/6191682
前面一章介绍了如何Binder的服务器端.
接下来就是如何实现客户端程序了.我们将要介绍的客户端可执行程序为Example
第1步:
在framework/base目录下新建一个ExampleClient目录,用以保存客户端源代码:
- $cd framework/base/
- $mkdir ExampleClient
- $cd ExampleClient/
第2步:
在 这个ExampleClient目录下有3个源文件:Example.h,Example.cpp,Android.mk
其中Example.h的文件内容如下:
- // File: Example.h
- #ifndef ANDROID_BYN_EXAMPLE_H
- #define ANDROID_BYN_EXAMPLE_H
- namespace android
- {
- class Example {
- public:
- void add100(int n);
- private:
- static const void getExampleService();
- };
- }; //namespace
- #endif // ANDROID_BYN_EXAMPLE_H
- // File: Example.cpp
- #include <binder/IServiceManager.h>
- #include <binder/IPCThreadState.h>
- #include "Example.h"
- namespace android
- {
- sp<IBinder> binder;
- void Example::add100(int n)
- {
- getExampleService();
- Parcel data, reply;
- int answer;
- data.writeInt32(getpid());
- data.writeInt32(n);
- LOGE("BpExampleService::create remote()->transact()/n");
- binder->transact(0, data, &reply);
- answer = reply.readInt32();
- printf("answner=%d/n", answer);
- return;
- }
- const void Example::getExampleService()
- {
- sp<IServiceManager> sm = defaultServiceManager();
- binder = sm->getService(String16("byn.example"));
- LOGE("Example::getExampleService %p/n",sm.get());
- if (binder == 0) {
- LOGW("ExampleService not published, waiting...");
- return;
- }
- }
- }; //namespace
- using namespace android;
- int main(int argc, char** argv)
- {
- Example* p = new Example();
- p->add100(1);
- return 0;
- }
- # File: Example
- LOCAL_PATH:= $(call my-dir)
- include $(CLEAR_VARS)
- LOCAL_SRC_FILES:= \
- Example.cpp
- LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
- LOCAL_SHARED_LIBRARIES := \
- libutils libbinder libExample
- LOCAL_MODULE_TAGS := optional
- LOCAL_PRELINK_MODULE := false
- LOCAL_MODULE := Example
- include $(BUILD_EXECUTABLE)
第3步:
编译Example可执行程序:
- $cd ~/WORKING_DIRECTORY/
- $mmm framework/base/ExampleClient
编译完后,在out/target/product/generic/system/bin/目录下可以看到可执行程序Example.
这样就表示生成客户端程序了,接下来就是验证我们的程序了.
第4步:
在Android源代码根目录下make 生成system.img文件
- $make snod
![](http://hi.csdn.net/attachment/201112/30/0_1325238728Narw.gif)
第5步:
启动模拟器并用adb连接
- $emulator&
- $adb shell
![](http://hi.csdn.net/attachment/201112/30/0_1325232250N2CC.gif)
第6步
在模拟器内,查看libExample.so,ExampleServer,Example三个文件.
- # ls system/lib/libEx*
- # ls system/bin/Examp
第7步:启动ExampleServer
- # ./system/bin/ExampleServer&
第8步:启动客户端程序Example程序
- # ./system/bin/Example
关于binder服务器端如何实现的请看博客内上一篇文章: http://blog.csdn.net/flydream0/article/details/7165127
完!