祝各位女神3.8快乐~最近在阅读Android源码的过程中再次遇到AIDL。和以往不同,这次是Java层和c++层的相互调用,跟以往App端的两个Java进程的IPC通信有区别。

笔者在先前已经简单的分析了AIDL,但是AIDL远不止这么JAVA-JAVA通信这么简单,事实上Android系统中可以通过binder,实现双向IPC通信,可以是JAVA - JAVA 、 JAVA - C++ 、 C++ - C++ ,都可以通过Binder进行IPC双向通信。本文主要通过JAVA-C++的通信更加深入了解AIDL。

1.Binder简介

Binder作为Android系统提供的一种IPC机制,这是Android系统中最重要的组成,也是最难理解的一块知识点,错综复杂。

Binder是Android整个系统的核心,考虑复杂性,暂时对其具体实现过程简单提下,具体需要在Binder篇章深入研究。

Binder系统架构图 Binder系统架构图

由于AIDL可以是C++层也可以是Java层,那么上述Binder通信的变体就会出现下面这几种。

1)两个App进程通信

两个App进程通信图 两个App进程通信图

2)一个App进程,一个Native进程通信

App和Native进程通信图 App和Native进程通信图

3)两个Native进程通信

两个Native进程通信图 两个Native进程通信图

结合代表性,本文主要对第二种情况的通信展开描述。

2.Binder核心类介绍和原理

2.1Binder框架

2.1.1Binder由四部分组成

Binder驱动:Binder的核心,实现底层操作

ServiceManager:守护进程,Binder服务的管理者

服务端:Binder的提供者Bn

客户端:Binder的使用者Bp

2.1.2Binder设计分层

Binder实现通过libbinder库实现。Binder源码点击这里

/frameworks/native/libs/binder

/frameworks/native/libs/binder
/frameworks/native/libs/binder/Binder.cpp
/frameworks/native/libs/binder/BpBinder.cpp
/frameworks/native/libs/binder/IInterface.cpp
/frameworks/native/libs/binder/IPCThreadState.cpp
/frameworks/native/libs/binder/ProcessState.cpp
/frameworks/native/libs/binder/Parcel.cpp
/frameworks/native/libs/binder/include/binder/Binder.h
/frameworks/native/libs/binder/include/binder/BpBinder.h
/frameworks/native/libs/binder/include/binder/IBinder.h
/frameworks/native/libs/binder/include/binder/IInterface.h
/frameworks/native/libs/binder/include/binder/IPCThreadState.h
/frameworks/native/libs/binder/include/binder/ProcessState.h
/frameworks/native/libs/binder/include/binder/Parcel.h

2.2Binder核心类

IIterface类,BpInterface类,BnInterface类,BBinder类,BpBinder类,IBinder类

2.2.1各类之间的继承

各类的继承关系

各类的继承关系图 各类的继承关系图

简化成客户端和服务端的关系

客户端和服务端的关系图 客户端和服务端的关系图

2.2.2服务端

以下为Android11源码分析

BnInterface类,开发Binder服务必须要继承的类

 1//frameworks/native/libs/binder/include/binder/IInterface.h#BnInterface
 2template<typename INTERFACE>
 3class BnInterface : public INTERFACE, public BBinder
 4{
 5public:
 6    virtual sp<IInterface>      queryLocalInterface(const String16& _descriptor);
 7    virtual const String16&     getInterfaceDescriptor() const;
 8
 9protected:
10    typedef INTERFACE           BaseInterface;
11    virtual IBinder*            onAsBinder();
12};

BBinder类,服务类的核心。这里的IBinder类前面的clang::lto_visibility_public详见这里

1//frameworks/native/libs/binder/include/binder/IBinder.h#transact
2class [[clang::lto_visibility_public]] IBinder : public virtual RefBase{
3    virtual status_t        transact(   uint32_t code,
4                                 const Parcel& data,
5                                 Parcel* reply,
6                                 uint32_t flags = 0) = 0;
7};

最终实现是在Binder

 1//frameworks/native/libs/binder/Binder.cpp#transact
 2status_t BBinder::transact(
 3    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 4{
 5    data.setDataPosition(0);
 6
 7    status_t err = NO_ERROR;
 8    switch (code) {
 9        case PING_TRANSACTION:
10            err = pingBinder();
11            break;
12        case EXTENSION_TRANSACTION:
13            err = reply->writeStrongBinder(getExtension());
14            break;
15        case DEBUG_PID_TRANSACTION:
16            err = reply->writeInt32(getDebugPid());
17            break;
18        default:
19            err = onTransact(code, data, reply, flags);
20            break;
21    }
22
23    // In case this is being transacted on in the same process.
24    if (reply != nullptr) {
25        reply->setDataPosition(0);
26    }
27
28    return err;
29}

其中BBinder负责和更底层的IPCThread交互,IPCThread会调用BBinder的transact方法,transact方法会调用到继承类中的onTransact方法实现交互。

因此,我们自己只需要对对BBinder的继承类重写onTransact方法,既可以实现数据与驱动交互。

 1//frameworks/native/libs/binder/Binder.cpp#onTransact
 2status_t BBinder::onTransact(
 3    uint32_t code, const Parcel& data, Parcel* reply, uint32_t /*flags*/)
 4{
 5    switch (code) {
 6        case INTERFACE_TRANSACTION:
 7            reply->writeString16(getInterfaceDescriptor());
 8            return NO_ERROR;
 9
10        case DUMP_TRANSACTION: {
11            int fd = data.readFileDescriptor();
12            int argc = data.readInt32();
13            Vector<String16> args;
14            for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
15               args.add(data.readString16());
16            }
17            return dump(fd, args);
18        }
19
20        case SHELL_COMMAND_TRANSACTION: {
21            int in = data.readFileDescriptor();
22            int out = data.readFileDescriptor();
23            int err = data.readFileDescriptor();
24            int argc = data.readInt32();
25            Vector<String16> args;
26            for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
27               args.add(data.readString16());
28            }
29            sp<IShellCallback> shellCallback = IShellCallback::asInterface(
30                    data.readStrongBinder());
31            sp<IResultReceiver> resultReceiver = IResultReceiver::asInterface(
32                    data.readStrongBinder());
33
34            // XXX can't add virtuals until binaries are updated.
35            //return shellCommand(in, out, err, args, resultReceiver);
36            (void)in;
37            (void)out;
38            (void)err;
39
40            if (resultReceiver != nullptr) {
41                resultReceiver->send(INVALID_OPERATION);
42            }
43
44            return NO_ERROR;
45        }
46
47        case SYSPROPS_TRANSACTION: {
48            report_sysprop_change();
49            return NO_ERROR;
50        }
51
52        default:
53            return UNKNOWN_TRANSACTION;
54    }
55}

2.2.3客户端

BpBinder

这个是客户端的核心

 1//frameworks/native/libs/binder/include/binder/IInterface.h#BpInterface
 2template<typename INTERFACE>
 3class BpInterface : public INTERFACE, public BpRefBase
 4{
 5public:
 6    explicit                    BpInterface(const sp<IBinder>& remote);
 7
 8protected:
 9    typedef INTERFACE           BaseInterface;
10    virtual IBinder*            onAsBinder();
11};

与BnBinder中BnInterface类继承BBinder不同的是,BpInterface类不是继承BpBinder的,而是继承BpRefBase类的。这个可以更加灵活地进行应用开发,BpBinder更改对客户端实现无影响。

 1//frameworks/native/libs/binder/include/binder/Binder.h#BpRefBase
 2class BpRefBase : public virtual RefBase
 3{
 4protected:
 5    explicit                BpRefBase(const sp<IBinder>& o);
 6    virtual                 ~BpRefBase();
 7    virtual void            onFirstRef();
 8    virtual void            onLastStrongRef(const void* id);
 9    virtual bool            onIncStrongAttempted(uint32_t flags, const void* id);
10
11    inline  IBinder*        remote()                { return mRemote; }
12    inline  IBinder*        remote() const          { return mRemote; }
13
14private:
15                            BpRefBase(const BpRefBase& o);
16    BpRefBase&              operator=(const BpRefBase& o);
17
18    IBinder* const          mRemote;
19    RefBase::weakref_type*  mRefs;
20    std::atomic<int32_t>    mState;
21};

BpBinder

负责与底层IPCThread交互,代理类中的函数实现会最终调用IBinder的transact,transact调用IPCThread函数向驱动传递数据。

1//frameworks/native/libs/binder/include/binder/BpBinder.h#transact
2class BpBinder : public IBinder{
3   virtual status_t    transact(   uint32_t code,
4                             const Parcel& data,
5                             Parcel* reply,
6                             uint32_t flags = 0) final; 
7};

最终实现在BpBinder.cpp

 1//frameworks/native/libs/binder/BpBinder.cpp#transact
 2status_t BpBinder::transact(
 3    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 4{
 5    // Once a binder has died, it will never come back to life.
 6    if (mAlive) {
 7        ...
 8        status_t status = IPCThreadState::self()->transact(
 9            mHandle, code, data, reply, flags);
10        if (status == DEAD_OBJECT) mAlive = 0;
11
12        return status;
13    }
14
15    return DEAD_OBJECT;
16}

Binder代理类

asInterface,实际上这个是宏定义出来的

 1//frameworks/native/libs/binder/include/binder/IInterface.h#DECLARE_META_INTERFACE
 2#define DECLARE_META_INTERFACE(INTERFACE)                               \
 3public:                                                                 \
 4    static const ::android::String16 descriptor;                        \
 5    static ::android::sp<I##INTERFACE> asInterface(                     \
 6            const ::android::sp<::android::IBinder>& obj);              \
 7    virtual const ::android::String16& getInterfaceDescriptor() const;  \
 8    I##INTERFACE();                                                     \
 9    virtual ~I##INTERFACE();                                            \
10    static bool setDefaultImpl(std::unique_ptr<I##INTERFACE> impl);     \
11    static const std::unique_ptr<I##INTERFACE>& getDefaultImpl();       \
12private:                                                                \
13    static std::unique_ptr<I##INTERFACE> default_impl;                  \
14public:                                                                 \

具体实现

 1//frameworks/native/libs/binder/include/binder/IInterface.h#DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE
 2#define DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE(INTERFACE, NAME)\
 3    ...
 4    ::android::sp<I##INTERFACE> I##INTERFACE::asInterface(              \
 5            const ::android::sp<::android::IBinder>& obj)               \
 6    {                                                                   \
 7        ::android::sp<I##INTERFACE> intr;                               \
 8        if (obj != nullptr) {                                           \
 9            intr = static_cast<I##INTERFACE*>(                          \
10                obj->queryLocalInterface(                               \
11                        I##INTERFACE::descriptor).get());               \
12            if (intr == nullptr) {                                      \
13                intr = new Bp##INTERFACE(obj);                          \
14            }                                                           \
15        }                                                               \
16        return intr;                                                    \
17    }                                                                   \

考虑到上述queryLocalInterface的入参,可以是BBinder,也可以是BpBinder,那么BnInterface中的实现,返回的是BnInterface实例它本身。

1//frameworks/native/libs/binder/include/binder/IInterface.h#BnInterface<INTERFACE>::queryLocalInterface
2template<typename INTERFACE>
3inline sp<IInterface> BnInterface<INTERFACE>::queryLocalInterface(
4        const String16& _descriptor)
5{
6    if (_descriptor == INTERFACE::descriptor) return this;
7    return nullptr;
8}

BpInterface的本身没有queryLocalInterface方法,它的构造BpInterface(const sp& remote);中的参数是IBinder类型,最终调用到的是IBinder中的queryLocalInterface方法。也就是BpInterface间接调用BpBinder,BpBinder的实现是返回nullptr,那么一定会调用new Bp##INTERFACE(obj);这里。客户端才能生成真正的代理类,服务端生成不了

1//frameworks/native/libs/binder/Binder.cpp#IBinder::queryLocalInterface
2sp<IInterface>  IBinder::queryLocalInterface(const String16& /*descriptor*/)
3{
4    return nullptr;
5}

2.2.4总结

BBinder是服务端的核心,BpBinder是客户端的核心,两者都是IBinder派生出来的,其中服务端需要实现BnInterface,客户端需要实现BpInterface。

2.3Binder死亡通知

检测一个服务,是不是宕机或者已经挂死,可以通过死亡通知来检测。

2.3.1linkToDeath

IBinder提供了一个死亡通知接口linkToDeath。

其有三个参数,recipient为接收对象,必须自定义实现。

1//frameworks/native/libs/binder/include/binder/IBinder.h#linkToDeath
2class [[clang::lto_visibility_public]] IBinder : public virtual RefBase{
3    virtual status_t        linkToDeath(const sp<DeathRecipient>& recipient,
4                                        void* cookie = nullptr,
5                                        uint32_t flags = 0) = 0;
6};

这个类DeathRecipient就是接口,用于回调,需要重载binderDied

1//frameworks/native/libs/binder/include/binder/IBinder.h#DeathRecipient
2class DeathRecipient : public virtual RefBase
3{
4    public:
5    virtual void binderDied(const wp<IBinder>& who) = 0;
6};

考虑到IBinder,既可以是BBinder,也可以是BpBinder。他们又有分别的实现。

BBinder

1//frameworks/native/libs/binder/Binder.cpp#linkToDeath
2status_t BBinder::linkToDeath(
3    const sp<DeathRecipient>& /*recipient*/, void* /*cookie*/,
4    uint32_t /*flags*/)
5{
6    return INVALID_OPERATION;
7}

BpBinder

 1//frameworks/native/libs/binder/BpBinder.cpp#linkToDeath
 2status_t BpBinder::linkToDeath(
 3    const sp<DeathRecipient>& recipient, void* cookie, uint32_t flags)
 4{
 5    Obituary ob;
 6    ob.recipient = recipient;
 7    ob.cookie = cookie;
 8    ob.flags = flags;
 9
10    LOG_ALWAYS_FATAL_IF(recipient == nullptr,
11                        "linkToDeath(): recipient must be non-NULL");
12
13    {
14        AutoMutex _l(mLock);
15
16        if (!mObitsSent) {
17            if (!mObituaries) {
18                mObituaries = new Vector<Obituary>;
19                if (!mObituaries) {
20                    return NO_MEMORY;
21                }
22                ALOGV("Requesting death notification: %p handle %d\n", this, mHandle);
23                getWeakRefs()->incWeak(this);
24                IPCThreadState* self = IPCThreadState::self();
25                self->requestDeathNotification(mHandle, this);
26                self->flushCommands();
27            }
28            ssize_t res = mObituaries->add(ob);
29            return res >= (ssize_t)NO_ERROR ? (status_t)NO_ERROR : res;
30        }
31    }
32
33    return DEAD_OBJECT;
34}

因此,只能在客户端接收死亡通知。

executeCommand

那么有了死亡通知的接口,那么谁来发送死亡通知呢?

这个死亡通知实际上是由驱动推送的,驱动检测某个服务死亡,会根据设置向应用推送消息。

 1//frameworks/native/libs/binder/IPCThreadState.cpp#executeCommand
 2status_t IPCThreadState::executeCommand(int32_t cmd)
 3{
 4    BBinder* obj;
 5    RefBase::weakref_type* refs;
 6    status_t result = NO_ERROR;
 7
 8    switch ((uint32_t)cmd) {
 9    ...
10    case BR_DEAD_BINDER:
11        {
12            BpBinder *proxy = (BpBinder*)mIn.readPointer();
13            proxy->sendObituary();
14            mOut.writeInt32(BC_DEAD_BINDER_DONE);
15            mOut.writePointer((uintptr_t)proxy);
16        } break;
17    ...
18    default:
19        ALOGE("*** BAD COMMAND %d received from Binder driver\n", cmd);
20        result = UNKNOWN_ERROR;
21        break;
22    }
23
24    if (result != NO_ERROR) {
25        mLastError = result;
26    }
27
28    return result;
29}

调用到BpBinder中的sendObituary方法

 1//frameworks/native/libs/binder/BpBinder.cpp#sendObituary
 2void BpBinder::sendObituary()
 3{
 4    ...
 5    if (obits != nullptr) {
 6        const size_t N = obits->size();
 7        for (size_t i=0; i<N; i++) {
 8            reportOneDeath(obits->itemAt(i));
 9        }
10
11        delete obits;
12    }
13}

而reportOneDeath最终会调用到上述死亡通知篇章中的回调函数binderDied,这也是为什么该函数必须重载。

1//frameworks/native/libs/binder/BpBinder.cpp#reportOneDeath
2void BpBinder::reportOneDeath(const Obituary& obit)
3{
4    sp<DeathRecipient> recipient = obit.recipient.promote();
5    ALOGV("Reporting death to recipient: %p\n", recipient.get());
6    if (recipient == nullptr) return;
7
8    recipient->binderDied(this);
9}

3.AIDL实战

1.接口扩展

 1//ITestService.h
 2#include <IInterface.h>
 3#define TEST_GET 1
 4#define TEST_SET 2
 5
 6namespace android{
 7Class ITestService : public IInterface{
 8public:
 9    DECLARE_META_INTERFACE(TestService);
10    virtual int get() = 0;
11    virtual void set(int value) = 0;
12};
13}

2.服务端

 1//BnTestService.h
 2namespace android{
 3class BnTestService : public BnInterface<ITestService>{
 4public:
 5    BnTestService();
 6public:
 7    int cnt = 0;
 8    virtual int get();
 9    virtual void set(int value);
10    virtual status_t onTransact(uint32_t code,
11                                const Parcel& data,
12                                Parcel* reply,
13                                uint32_t flags = 0);
14};
15}

3.客户端

 1#BpTestService.h
 2namespace android{
 3class BpTestService : public BpInterface<ITestService>{
 4public:
 5    BpTestService::BpTestService(const sp<IBinder>& impl) : BpInterface<ITestService>(impl);
 6public:
 7    virtual int get();
 8    virtual void set(int value);
 9};
10}

3.Bn端的代码实现

 1//BnTestService.cpp
 2#include "BnTestService.h"
 3BnTestService::BnTestService()
 4{
 5}
 6
 7status_t BnTestService::onTransact(uint32_t code,
 8                                const Parcel& data,
 9                                Parcel* reply,
10                                uint32_t flags = 0)
11{
12    switch() {
13        case TEST_GET: {
14           //数据有效性检测 
15           CHECK_INTERFACE(ITestService, data, reply);
16           set(data->readInt());
17           return NO_ERROR;
18        } break;
19        case TEST_SET: {
20           //数据有效性检测 
21           CHECK_INTERFACE(ITestService, data, reply);
22           reply->writeInt(get());
23           return NO_ERROR;
24        } break;
25        default:
26            return IBinder::onTransact(code, data, reply, flag);
27    }
28}
29
30int BnTestService::get()
31{
32    return cnt;
33}
34
35void BnTestService::set(int cnt)
36{
37    this->cnt = cnt;
38}

4.Bp端的代码实现

 1namespace android{
 2IMPLEMENT_META_INTERFACE(ITestService, "android.test.ITestService");
 3
 4BpTestService::BpTestService(const sp<IBinder>& impl) : BpInterface<ITestService>(impl)
 5{
 6}
 7
 8int BpTestService::get()
 9{
10    Parcel data, reply;
11    remote()->transact(TEST_GET, data, &reply);
12    return reply.readInt();
13}
14
15void BpTestService::set(int cnt)
16{
17    Parcel data, reply;
18    data.writeInt(cnt);
19    remote()->transact(TEST_SET, data, &reply);
20}     
21}

Bp中的remote(),就是mRemote,而mRemote是在Bp构造的时候传入的impl,即为BpBinder的一个实例。

1//frameworks/native/libs/binder/include/binder/Binder.h#BpRefBase::remote
2inline  IBinder*        remote()                { return mRemote; }

4.系统源码实例分析

事实上,源码中有大量的使用这类AIDL的方式。

Android Camera AIDL图 Android Camera AIDL图

举一个比较常见的代码,Camera源码中Camera App调用到CameraService里面的功能,这个时候用得就是AIDL。

Camera架构图 Camera架构图

4.1 addListener

这里调用了cameraService中的addListener方法,但实际上最终实现是在CameraService.cpp中的addListener函数。

 1//base/core/java/android/hardware/camera2/CameraManager.java#connectCameraServiceLocked
 2private void connectCameraServiceLocked() {
 3    if (mCameraService != null || sCameraServiceDisabled) return;
 4    Log.i(TAG, "Connecting to camera service");
 5
 6    IBinder cameraServiceBinder = ServiceManager.getService(CAMERA_SERVICE_BINDER_NAME);
 7    ICameraService cameraService = ICameraService.Stub.asInterface(cameraServiceBinder);
 8    ...
 9    try {
10        CameraStatus[] cameraStatuses = cameraService.addListener(this);
11        for (CameraStatus c : cameraStatuses) {
12            onStatusChangedLocked(c.status, c.cameraId);
13
14            if (c.unavailablePhysicalCameras != null) {
15                for (String unavailPhysicalCamera : c.unavailablePhysicalCameras) {
16                    onPhysicalCameraStatusChangedLocked(
17                        ICameraServiceListener.STATUS_NOT_PRESENT,
18                        c.cameraId, unavailPhysicalCamera);
19                }
20            }
21        }
22        mCameraService = cameraService;
23    }
24    ...
25}

4.2 系统AIDL组成结构

4.2.1 AIDL定义

 1//frameworks/av/camera/aidl/android/hardware/ICameraService.aidl
 2interface ICameraService {
 3    /**
 4     * Add listener for changes to camera device and flashlight state.
 5     *
 6     * Also returns the set of currently-known camera IDs and state of each device.
 7     * Adding a listener will trigger the torch status listener to fire for all
 8     * devices that have a flash unit.
 9     */
10    CameraStatus[] addListener(ICameraServiceListener listener);
11    ...
12}

4.2.2 生成的AIDL的java接口

这部分需要编译frameworks之后才能在/out目录下生成对应的java文件。这个java文件跟在as定义之后生成的java文件类似。

 1///out/target/common/obj/JAVA_LIBRARIES/framework_intermediates/dotdot/av/camera.aidl/amdroid/hardware/ICameraService.java#ICmaeraService
 2public interface ICmaeraService extends android.os.IInterface
 3{
 4    ...
 5    private static class Proxy implements android.hardware.ICameraService
 6    {
 7        private android.os.IBinder mRemote;
 8        Proxy(android.os.IBinder remote)
 9        {
10            mRemote = remote;
11        }
12        
13        @override
14        public android.hardware.CameraStatus[] addListener(android.hardware.ICameraServiceListener listener)
15            throws android.os.RemoteException
16        {
17            android.os.Parcel _data = android.os.Parcel.obtain();
18            android.os.Parcel _reply = android.os.Parcel.obtain();
19            android.hardware.CameraStatus[] _result;
20            try
21            {
22                _data.writeInterfaceToken(DESCRIPTOR);
23                _data.writeStrongBinder((((listener != null)) ? (listener.asBinder()) : (null)));
24                mRemote.transact(Stub.TRANSACTION_addListener, _data, _reply, 0);
25                _reply.readException();
26                _result = _reply.createTypedArray(android.hardware.CameraStatus.CREATOR);
27            }
28            finally
29            {
30                _reply.recycle();
31                _data.recycle();
32            }
33            return _result;
34        }
35    }
36    ...
37}

4.2.3 生成的AIDL的c++接口

这里的接口主要有三个,分别是Bp,Bn和I(BpCameraService.h,BnCameraService.h,ICameraService.h)。

这里有两种对应的路径,分别对应32位(android_arm_armv7-a)和64位(android_arm64_armv8-a),笔者这里以64位举例说明。

ICameraService.h

 1///out/soong/.intermediates/frameworks/av/camera/libcamera_client/android_arm64_armv8_xxx/gen/aidl/android/hardware/ICameraService.h
 2Class ICameraService : public ::android::IInterface
 3{
 4public:
 5    DECLARE_META_INTERFACE(CameraService);
 6    virtual ::android::binder::Status addListener(const ::android::sp<::android::hardware::ICameraServiceListener>& listener, ::std::vector<::android::hardware::CameraStatus>* _aidl_return) = 0;
 7    enum Call{
 8        ADDLISTENER = ::android::IBinder::FIRST_CALL_TRANSACTION + 5;
 9    };
10    ...
11};

BpCameraService.h

1///out/soong/.intermediates/frameworks/av/camera/libcamera_client/android_arm64_armv8_xxx/gen/aidl/android/hardware/BpCameraService.h
2class BpCameraService : public ::android::BnInterface<ICameraService>
3{
4public:
5    explicit BpCameraService(const ::android::sp<::android::IBinder>& _aidl_impl;
6    virtual ~BpCameraService() = default;
7    ::android::binder::Status addListener(const ::android::sp<::android::hardware::ICameraServiceListener>& listener, ::std::vector<::android::hardware::CameraStatus>* _aidl_return) override;
8    ...
9};

BnCameraService.h

1///out/soong/.intermediates/frameworks/av/camera/libcamera_client/android_arm64_armv8_xxx/gen/aidl/android/hardware/BnCameraService.h
2class BnCameraService : public ::android::BnInterface<ICameraService>
3{
4public:
5    ::android::status_t BnCameraService::onTransact(uint32_t _aidl_code, 
6                                                    const ::android::Parcel& _aidl_data,
7                                                    ::android::Parcel* _aidl_reply,
8                                                    uint32_t _aidl_flags = 0) override;
9};

4.2.4生成的AIDL的c++实现

 1///out/soong/.intermediates/frameworks/av/camera/libcamera_client/android_arm64_armv8_xxx/gen/aidl/frameworks/av/camera/aidl/android/hardware/ICameraService.cpp
 2::android::status_t BnCameraService::onTransact(uint32_t _aidl_code, 
 3                                                const ::android::Parcel& _aidl_data,
 4                                                ::android::Parcel* _aidl_reply,
 5                                                uint32_t _aidl_flags){
 6    ::android::status_t _aidl_ret_status = ::android::OK;
 7    switch (_aidl_code){
 8        case Call::ADDLISTENER:
 9            {
10                ::android::sp<::android::hardware::ICameraServiceListener> in_listener;
11                ::std::vector<::android::hardware::CameraStatus> _aidl_return;
12                if (!(_aidl_data.checkInterface(this))){
13                    _aidl_ret_status = ::android::BAD_TYPE;
14                    break;
15                }
16                _aidl_ret_status = _aidl_data.readStrongBinder(&in_listener);
17                if (((_aidl_ret_status) != (::android::OK))){
18                    break;
19                }
20
21                ::android::Binder::Status _aidl_status(addListener(in_listener, &_aidl_return));
22                _aidl_ret_status = _aidl_status.writeToParcel(_aidl_reply);
23
24                if (((_aidl_ret_status) != (::android::OK))){
25                    break;
26                }
27                if (!_aidl_status.isOk()){
28                    break;
29                }
30                _aidl_ret_status = _aidl_reply->writeParcelableVector(_aidl_return
31                                                                     );
32                if (((_aidl_ret_status) != (::android::OK))){
33                    break;
34                }
35            }break; 
36    }
37}

4.2.5最终的服务实现

最终会调用到cpp继承的库libcameraservice,这里的libcameraservice中有很多目录。这里面会分别对应api接口和device接口,而调用这些借口的正是CameraService,所以我们这个libcameraservice这个库可以看做成由CameraService作为外观者模式,其余函数用于真正实现的库。

libcameraservice树状结构图 libcameraservice树状结构图
 1//frameworks/av/services/camera/libcameraservice/CameraService.h
 2class CameraService :
 3    public BinderService<CameraService>,
 4    public virtual ::android::hardware::BnCameraService,
 5    public virtual IBinder::DeathRecipient,
 6    public virtual CameraProviderManager::StatusListener
 7    {
 8        virtual binder::Status    addListener(const sp<hardware::ICameraServiceListener>& listener,
 9                                              /*out*/
10                                              std::vector<hardware::CameraStatus>* cameraStatuses);
11        ...
12};

最终实现是在这里CameraService.cpp,具体里面的实现内容就不展开描述,主要是梳理aidl的流程。

1//frameworks/av/services/camera/libcameraservice/CameraService.cpp
2Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3        /*out*/
4        std::vector<hardware::CameraStatus> *cameraStatuses) {
5    return addListenerHelper(listener, cameraStatuses);
6}

4.3总结

系统源码Camrea Frameworks中的框架的调用,是从上层的app应用调用到sdk jar包中,这个jar包调用到CameraManager,而CameraManager内部去通过aidl方式获取CameraService的实例,并通过这个实例调用addListener方法,最终这个方法调用到libcameraservice中的CameraService.cpp。

Camera aidl继承关系图 Camera aidl继承关系图

除此之外,更加细节的调用如下图所示。

Camera aidl调用关系 Camera aidl调用关系

参考

[1] gcwl2016, Android系统中通过binder(AIDL)进行跨层IPC通信, 2019.

[2] i加加, (五十七)Android O WiFi的扫描流程梳理续——梳理java与c++之间的aidl-cpp通信, 2018.

[3] 飞同小可,android系统开发binder调用(C++和java相互调用), 2018.

[4] aaajj, c++层使用和编译aidl文件例子, 2019.

[5] SherlockCharlie, Android8.0 Binder之面向系统服务(二), 2018.

[6] 躬行之, Android进阶之AIDL的使用详解, 2018.

[7] 袁辉辉, Binder系列—开篇, 2015.

[8] rockmanlc, IBinder类前面的clang::lto_visibility_public, 2021.

[9] syfchao, Android基础框架Binder应用开发(一)-BnBp服务实现, 2021.

[10] 程序员Android, Camera2 / HAL3 架构了解下,2020

[11] zhuyong006, Camera 初始化(Open)一(FrameWork -> Hal),2019