前面一章介紹了如何Binder的服務器端. 見 http://www.linuxidc.com/Linux/2012-01/50766.htm
接下來就是如何實現客戶端程序了.我們將要介紹的客戶端可執行程序為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
Example.cpp的文件內容如下:
- // 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;
- }
Android.mk文件的內容如下:
- # 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.
這樣就表示生成客戶端程序了,接下來就是驗證我們的程序了.