C++與Java之間的Binder通信

簡介

在Android系統(tǒng)開發(fā)中經(jīng)常會碰到server端和client語言不同問題,例如使用C++編寫的Service洽故,客戶端是Java/Kotlin;或者是app中創(chuàng)建的Service,client端是c++的情況广恢,本篇文章介紹使用C/C++編寫的程序如何與Java編寫的Service進行binder通信欣孤。

  1. Binder通信首先創(chuàng)建AIDL文件馋没,用于定義服務(wù)端的接口,這里簡單示例:
// server
package com.lu.test;
import com.lu.test.ITestClient;

interface ITestService{
    String getServiceName();
    void registerClient(ITestClient client);
}

//client
package com.lu.test;

interface ITestClient{
    String getClientName();
}
  1. 編寫腳本用于生成c層的頭文件(java可以通過Android Studio 生成相關(guān)的類)
  cc_library_shared {
    name: "lib-test",
    srcs:["./**/*.aidl"],
    aidl:{
        include_dirs:["./"],
    },
    shared_libs:[
        "libutils",
        "libcutils",
        "libbinder",
    ],
}

我們當(dāng)前的目錄結(jié)構(gòu)如下:

├── Android.bp
└── com
    └── lu
        └── test
            ├── ITestClient.aidl
            └── ITestService.aidl

將該部分文件放入到aosp下降传,可以放在vendor底下篷朵,然后運行在根目錄運行:

make lib-test

即可得到頭文件:

# 生成的頭文件路徑
# out/soong/.intermediates/vendor/test/lib-test/android_arm64_armv8-a_shared/gen

生成的文件列表

.
└── com
    └── lu
        └── test
            ├── BnTestClient.h
            ├── BnTestService.h
            ├── BpTestClient.h
            ├── BpTestService.h
            ├── ITestClient.cpp
            ├── ITestClient.cpp.d
            ├── ITestClient.h
            ├── ITestService.cpp
            └── ITestService.h

其中Bn開頭的是作為Binder中的server端的頭文件,需要我們?nèi)崿F(xiàn)婆排;Bp打頭的文件類似于Java中的Stub声旺,用于做類型轉(zhuǎn)換的代理類。

  1. 實現(xiàn)Bn段只,在這個例子中腮猖,我們是需要雙向通信的,client端獲取ItestService訪問server端赞枕,同時像server端注冊ITestClient澈缺,server端通過ITestClient可以訪問client端;
  • Server端通過Java實現(xiàn)ITestService,使用AS創(chuàng)建一個App鹦赎,并且編寫一個Service即可:
private const val TAG = "TestService"

class TestService : Service() {

    private val mService = object : ITestService.Stub() {
        override fun getServiceName(): String {
            return "TestService";
        }

        override fun registerClient(client: ITestClient) {
            Log.d(TAG, "registerClient : ${client.clientName}")
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        return mService
    }

    override fun onCreate() {
        super.onCreate()
        //將service添加到ServiceManager管理中
        ServiceManager.addService("BinderTest", mService)
    }
}
  • Client端通過C++實現(xiàn)ITestClient
    首先我們看下通過AIDL生成的ITestClient.h
#pragma once

#include <binder/IBinder.h>
#include <binder/IInterface.h>
#include <binder/Status.h>
#include <utils/String16.h>
#include <utils/StrongPointer.h>

namespace com {

namespace lu {

namespace test {

class ITestClient : public ::android::IInterface {
public:
  DECLARE_META_INTERFACE(TestClient)
  virtual ::android::binder::Status getClientName(::android::String16* _aidl_return) = 0;
};  // class ITestClient

class ITestClientDefault : public ITestClient {
public:
  ::android::IBinder* onAsBinder() override {
    return nullptr;
  }
  ::android::binder::Status getClientName(::android::String16*) override {
    return ::android::binder::Status::fromStatusT(::android::UNKNOWN_TRANSACTION);
  }
};  // class ITestClientDefault

}  // namespace test

}  // namespace lu

}  // namespace com

創(chuàng)建一個文件TestClient.h

#ifndef BINDERTEST_TESTCLIENT_H
#define BINDERTEST_TESTCLIENT_H

#include "com/lu/test/BnTestClient.h"

//此處繼承的是BnTestClient谍椅,這個類幫助我們實現(xiàn)了binder接口的轉(zhuǎn)化
class TestClient : public ::com::lu::test::BnTestClient {
public:
    TestClient();

    virtual ~TestClient();

    ::android::binder::Status getClientName(::android::String16 *_aidl_return);
};

#endif //BINDERTEST_TESTCLIENT_H

創(chuàng)建TestClient.cpp

#include "TestClient.h"

using namespace com::lu::test;

TestClient::TestClient() = default;

TestClient::~TestClient() = default;

::android::binder::Status TestClient::getClientName(::android::String16* _aidl_return){
    *_aidl_return = android::String16("TestClient");
   return android::binder::Status::ok();
}
  1. 編寫client端的測試程序TestMain.cpp
#include <unistd.h>
#include "binder/IBinder.h"
#include "utils/StrongPointer.h"
#include "binder/IServiceManager.h"
#include <android/binder_manager.h>
#include <android/binder_process.h>
#include "com/lu/test/ITestService.h"
#include "android_log_define.h"
#include "TestClient.h"
#include "thread"

#define SERVER_NAME  "BinderTest"

using namespace std;
using namespace android;

TestClient *clientImpl = new TestClient();;

android::sp<com::lu::test::ITestService> getService() {
    sp<IServiceManager> sm = defaultServiceManager();
    if (sm == nullptr) {
        LOGE("can't get serviceManager");
        return nullptr;
    }
    auto binder = sm->getService(String16(SERVER_NAME));
    if (binder == nullptr) {
        LOGE("can not get binder");
        return nullptr;
    }

    auto logServer = interface_cast<com::lu::test::ITestService>(binder);
    if (logServer == nullptr) {
        LOGE("can't cast LogServer");
        return nullptr;
    }

    return logServer;
}

int main() {
    auto service = getService();
    if (service == nullptr) {
        LOGE("registerService failed service is null");
        return -1;
    }
    service->registerClient(clientImpl);
    auto name = new String16();
    service->getServiceName(name);
    LOGD("the service name is %s", name->string());
    //這2句是使當(dāng)前線程具有binder的能力,會阻塞住當(dāng)前線程古话,建議可以放到子線程中
    ABinderProcess_setThreadPoolMaxThreadCount(0);
    ABinderProcess_joinThreadPool();
}

編譯腳本

cc_binary {
    name: "BindClientTest",
    srcs:[
        "./**/*.cpp"
    ],
    local_include_dirs:[
        "./include",
    ],
    shared_libs:[
        "libutils",
        "libcutils",
        "libbinder",
        "liblog",
        "libbase",
        "libbinder_ndk"
    ],
    cflags: [
        "-Wall",
        "-Werror",
        "-Wextra",
        "-Wno-unused-parameter",
        "-std=c++11",
        "-frtti",
        "-fexceptions",
        "-fPIC",
    ],
}

目錄結(jié)構(gòu)

├── Android.bp
├── TestClient.cpp
├── TestMain.cpp
└── include
    ├── TestClient.h
    ├── android_log_define.h
    └── com
        └── lu
            └── test
                ├── BnTestClient.h
                ├── BnTestService.h
                ├── BpTestClient.h
                ├── BpTestService.h
                ├── ITestClient.cpp
                ├── ITestClient.cpp.d
                ├── ITestClient.h
                ├── ITestService.cpp
                └── ITestService.h

  1. 調(diào)試
  • 將Server端的app運行起來
  • 將client端放入aosp環(huán)境編譯雏吭,產(chǎn)物推到system/bin/目錄下并運行
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市陪踩,隨后出現(xiàn)的幾起案子杖们,更是在濱河造成了極大的恐慌,老刑警劉巖肩狂,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件摘完,死亡現(xiàn)場離奇詭異,居然都是意外死亡傻谁,警方通過查閱死者的電腦和手機孝治,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人谈飒,你說我怎么就攤上這事岂座。” “怎么了杭措?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵费什,是天一觀的道長。 經(jīng)常有香客問我手素,道長鸳址,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任泉懦,我火速辦了婚禮稿黍,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘祠斧。我一直安慰自己闻察,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布琢锋。 她就那樣靜靜地躺著,像睡著了一般呢灶。 火紅的嫁衣襯著肌膚如雪吴超。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天鸯乃,我揣著相機與錄音鲸阻,去河邊找鬼。 笑死缨睡,一個胖子當(dāng)著我的面吹牛鸟悴,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播奖年,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼细诸,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了陋守?” 一聲冷哼從身側(cè)響起震贵,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎水评,沒想到半個月后猩系,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡中燥,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年寇甸,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡拿霉,死狀恐怖式塌,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情友浸,我是刑警寧澤峰尝,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站收恢,受9級特大地震影響武学,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜伦意,卻給世界環(huán)境...
    茶點故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一火窒、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧驮肉,春花似錦熏矿、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至卵渴,卻和暖如春慧域,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背浪读。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工昔榴, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人碘橘。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓互订,卻偏偏與公主長得像,于是被迫代替她去往敵國和親痘拆。 傳聞我的和親對象是個殘疾皇子仰禽,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內(nèi)容