歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 手把手教你如何實現Binder的客戶端程序(圖文)

手把手教你如何實現Binder的客戶端程序(圖文)

日期:2017/3/1 10:41:14   编辑:Linux編程

前面一章介紹了如何Binder的服務器端. 見 http://www.linuxidc.com/Linux/2012-01/50766.htm

接下來就是如何實現客戶端程序了.我們將要介紹的客戶端可執行程序為Example

第1步:

在framework/base目錄下新建一個ExampleClient目錄,用以保存客戶端源代碼:

  1. $cd framework/base/
  2. $mkdir ExampleClient
  3. $cd ExampleClient/

第2步:

在 這個ExampleClient目錄下有3個源文件:Example.h,Example.cpp,Android.mk

其中Example.h的文件內容如下:

  1. // File: Example.h
  2. #ifndef ANDROID_BYN_EXAMPLE_H
  3. #define ANDROID_BYN_EXAMPLE_H
  4. namespace android
  5. {
  6. class Example {
  7. public:
  8. void add100(int n);
  9. private:
  10. static const void getExampleService();
  11. };
  12. }; //namespace
  13. #endif // ANDROID_BYN_EXAMPLE_H
Example.cpp的文件內容如下:
  1. // File: Example.cpp
  2. #include <binder/IServiceManager.h>
  3. #include <binder/IPCThreadState.h>
  4. #include "Example.h"
  5. namespace android
  6. {
  7. sp<IBinder> binder;
  8. void Example::add100(int n)
  9. {
  10. getExampleService();
  11. Parcel data, reply;
  12. int answer;
  13. data.writeInt32(getpid());
  14. data.writeInt32(n);
  15. LOGE("BpExampleService::create remote()->transact()/n");
  16. binder->transact(0, data, &reply);
  17. answer = reply.readInt32();
  18. printf("answner=%d/n", answer);
  19. return;
  20. }
  21. const void Example::getExampleService()
  22. {
  23. sp<IServiceManager> sm = defaultServiceManager();
  24. binder = sm->getService(String16("byn.example"));
  25. LOGE("Example::getExampleService %p/n",sm.get());
  26. if (binder == 0) {
  27. LOGW("ExampleService not published, waiting...");
  28. return;
  29. }
  30. }
  31. }; //namespace
  32. using namespace android;
  33. int main(int argc, char** argv)
  34. {
  35. Example* p = new Example();
  36. p->add100(1);
  37. return 0;
  38. }
Android.mk文件的內容如下:
  1. # File: Example
  2. LOCAL_PATH:= $(call my-dir)
  3. include $(CLEAR_VARS)
  4. LOCAL_SRC_FILES:= \
  5. Example.cpp
  6. LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
  7. LOCAL_SHARED_LIBRARIES := \
  8. libutils libbinder libExample
  9. LOCAL_MODULE_TAGS := optional
  10. LOCAL_PRELINK_MODULE := false
  11. LOCAL_MODULE := Example
  12. include $(BUILD_EXECUTABLE)

第3步:

編譯Example可執行程序:

  1. $cd ~/WORKING_DIRECTORY/
  2. $mmm framework/base/ExampleClient
如下圖:

編譯完後,在out/target/product/generic/system/bin/目錄下可以看到可執行程序Example.

這樣就表示生成客戶端程序了,接下來就是驗證我們的程序了.

Copyright © Linux教程網 All Rights Reserved