Android native service实现(含Callback)

一、增加头文件

android/frameworks/av/include/mycore/IDeviceMac.h

#ifndef _IDEVICEMAC_H
#define _IDEVICEMAC_H

#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <utils/String8.h>
#include <android/log.h>

#define SERVER_NAME "demo.DeviceMacService"

namespace android
{
class IDataReaderCallback;

class IDeviceMac : public IInterface
{
public:
    enum
    {
        SET_BT_MAC = IBinder::FIRST_CALL_TRANSACTION,
        GET_BT_MAC,
        SET_DATA_READER_CALLBACK,
    };

    virtual int setBtMac(String8 btMac) = 0;

    virtual String8 getBtMac() = 0;

    virtual void setDataReaderCallback(const sp<IDataReaderCallback>& callback) = 0;

    DECLARE_META_INTERFACE(DeviceMac);
};

class BnDeviceMac : public BnInterface<IDeviceMac>
{
public:
    virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
    
};



} // end namespace android


#endif

android/frameworks/av/include/mycore/IDataReaderCallback.h

#ifndef _IDATA_READER_CALLBACK_H
#define _IDATA_READER_CALLBACK_H

#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <utils/String16.h>
#include <android/log.h>

namespace android
{
class IDataReaderCallback : public IInterface
{
public:
    enum
    {
        TRANSACT_ON_GET_DATA = IBinder::FIRST_CALL_TRANSACTION + 0,
    };
    virtual void onGetData(String16 str) = 0;

    DECLARE_META_INTERFACE(DataReaderCallback); // declare macro

};


class BnDataReaderCallback : public BnInterface<IDataReaderCallback>
{
public:
    virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
    
};

}  // end namespace android

#endif

二、实现Bp和Bn端代码,并打包成库

android/frameworks/av/libmycore/IDataReaderCallback.cpp 

#define LOG_TAG "DeviceMacBpDataReaderCallback"
#include <utils/Log.h>

#include <mycore/IDataReaderCallback.h>

namespace android
{
class BpDataReaderCallback : public BpInterface<IDataReaderCallback>
{
public:
    BpDataReaderCallback(const sp<IBinder>& impl) : BpInterface<IDataReaderCallback>(impl) {
    }

    void onGetData(String16 str) {
        printf("BpDataReaderCallback onGetData\n");
        Parcel data, reply;
        data.writeInterfaceToken(IDataReaderCallback::getInterfaceDescriptor());
        data.writeString16(str);
        remote()->transact(TRANSACT_ON_GET_DATA, data, &reply);
    }

};

IMPLEMENT_META_INTERFACE(DataReaderCallback,"DataReaderCallback");


status_t BnDataReaderCallback::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
    CHECK_INTERFACE(IDataReaderCallback, data, reply);
    ALOGI("BnDataReaderCallback onTransact code: %d", code);
    switch(code)
    {
        case TRANSACT_ON_GET_DATA:
            onGetData(data.readString16());
            return NO_ERROR;
        default:
            return BBinder::onTransact(code, data, reply, flags);
    }

}


}; // end namespace android

android/frameworks/av/libmycore/IDeviceMac.cpp

#define LOG_TAG "BpDeviceMac"
#include <utils/Log.h>
#include <mycore/IDeviceMac.h>
#include <mycore/IDataReaderCallback.h>

namespace android
{
class BpDeviceMac : public BpInterface<IDeviceMac>
{
public:
    BpDeviceMac(const sp<IBinder>& impl) : BpInterface<IDeviceMac>(impl)
    {

    }

    int setBtMac(String8 btMac)
    {
        ALOGI("Bp setBtMac");
        Parcel data, reply;
        data.writeInterfaceToken(IDeviceMac::getInterfaceDescriptor());
        data.writeString8(btMac);
        remote()->transact(SET_BT_MAC, data, &reply);
        return reply.readInt32();
    }

    String8 getBtMac()
    {
        ALOGI("Bp getBtMac");
        Parcel data, reply;
        data.writeInterfaceToken(IDeviceMac::getInterfaceDescriptor());
        remote()->transact(GET_BT_MAC, data, &reply);
        return reply.readString8();
    }

    void setDataReaderCallback(const sp<IDataReaderCallback>& callback)
    {
        ALOGI("Bp setDataReaderCallback");
        Parcel data, reply;
        data.writeInterfaceToken(IDeviceMac::getInterfaceDescriptor());
        data.writeStrongBinder(IInterface::asBinder(callback));
        remote()->transact(SET_DATA_READER_CALLBACK, data, &reply);
    }

};

IMPLEMENT_META_INTERFACE(DeviceMac, "DeviceMac");
/* Macro above expands to code below.
const android::String16 IDeviceMac::descriptor("DeviceMac");
const android::String16& IDeviceMac::getInterfaceDescriptor() const {
    return IDeviceMac::descriptor;
}
android::sp<IDeviceMac> IDeviceMac::asInterface(const android::sp<android::IBinder>& obj) {
    android::sp<IDeviceMac> intr;
    if (obj != NULL) {
        intr = static_cast<IDeviceMac*>(obj->queryLocalInterface(IDeviceMac::descriptor).get());
        if (intr == NULL) {
            intr = new BpDeviceMac(obj);
        }
    }
    return intr;
}
*/

status_t BnDeviceMac::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
    CHECK_INTERFACE(IDeviceMac, data, reply);
    ALOGI("Bn onTransact code: %d", code);
    switch(code)
    {
        case SET_BT_MAC:
            reply->writeInt32(setBtMac(data.readString8()));
            return NO_ERROR;
        case GET_BT_MAC:
            reply->writeString8(getBtMac());
            return NO_ERROR;
        case SET_DATA_READER_CALLBACK:{
            sp<IDataReaderCallback> client = interface_cast<IDataReaderCallback>(data.readStrongBinder());
            setDataReaderCallback(client);
            reply->writeInt32(12);
            return NO_ERROR;
        }break;
        default:
            return BBinder::onTransact(code, data, reply, flags);
    }

}


}; // end namespace android

android/frameworks/av/libmycore/Android.mk

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

LOCAL_SRC_FILES:= \
    IDeviceMac.cpp \
    IDataReaderCallback.cpp

LOCAL_SHARED_LIBRARIES := \
    libcutils \
    libutils \
    liblog \
    libbinder

LOCAL_MODULE:= libmycore

include $(BUILD_SHARED_LIBRARY)

三、实现service和client端

1、service端代码

android/frameworks/av/services/mycore/DeviceMacService.h

#ifndef _DEVICESERVICE_H
#define _DEVICESERVICE_H

#include <mycore/IDeviceMac.h>
#include <mycore/IDataReaderCallback.h>

namespace android{

class DeviceMacService : public BnDeviceMac
{
public:
    static void instantiate();
    
    DeviceMacService();
    virtual ~DeviceMacService();

    // IDeviceMac
    virtual int setBtMac(String8 btMac);
    virtual String8 getBtMac();
    virtual void setDataReaderCallback(const sp<IDataReaderCallback>& callback);

private:
    sp<IDataReaderCallback> mCallback = NULL;
    String8 mBtMac;
};

}; // end namespace android

#endif


android/frameworks/av/services/mycore/DeviceMacService.cpp

#define LOG_TAG "DeviceMacService"

#include <utils/Log.h>
#include <binder/IServiceManager.h>

#include "DeviceMacService.h"

namespace android
{
  DeviceMacService::DeviceMacService()
  {

  }

  DeviceMacService::~DeviceMacService()
  {

  }

  void DeviceMacService::instantiate()
  {
      ALOGI("DeviceMacService::instantiate");
      defaultServiceManager()->addService(String16(SERVER_NAME), new DeviceMacService());
  }

  int DeviceMacService::setBtMac(String8 btMac)
  {
      ALOGI("Bn setBtMac, btMac: %s", btMac.string());
      mBtMac = btMac;
      return NO_ERROR;
  }

  String8 DeviceMacService::getBtMac()
  {
      ALOGI("Bn getBtMac");
      if (mCallback != NULL)
      {
           ALOGI("Bn mCallback != NULL");
          mCallback->onGetData(String16("callback data...."));
      }
      if (mBtMac)
      {
          return mBtMac;
      }

      return String8("ff:ff:ff:ff:ff");
  }

  void DeviceMacService::setDataReaderCallback(const sp<IDataReaderCallback>& callback)
  {
      ALOGI("Bn setDataReaderCallback");
      if (callback != NULL)
      {
          mCallback = callback;
      }
  }

}; // end namespace android


android/frameworks/av/services/mycore/main_devicemacservice.cpp

#include <binder/ProcessState.h>
#include <binder/IServiceManager.h>
#include <binder/IPCThreadState.h>

#include "DeviceMacService.h"


using namespace android;

/**
* 启动服务
*/
int main(int argc, char** argv){
    sp<ProcessState> proc(ProcessState::self());
    DeviceMacService::instantiate();
    ProcessState::self()->startThreadPool();
    IPCThreadState::self()->joinThreadPool();
    return 0;
}

2、client端代码

android/frameworks/av/services/mycore/DataReaderCallback.h

#ifndef _DEVICESERVICE_H
#define _DEVICESERVICE_H

#include <mycore/IDataReaderCallback.h>

namespace android
{

class DataReaderCallback : public BnDataReaderCallback
{
public:
    
    DataReaderCallback();
    virtual ~DataReaderCallback();

    // IDataReaderCallback
    virtual void onGetData(String16 str);

};

}; // end namespace android

#endif

android/frameworks/av/services/mycore/DeviceMacClient.cpp

#define LOG_TAG "DeviceMacDataReaderCallback"

#include <utils/Log.h>
#include <binder/ProcessState.h>
#include <binder/IServiceManager.h>
#include <binder/IPCThreadState.h>

#include <mycore/IDeviceMac.h>

#include "DataReaderCallback.h"

using namespace android;

String16 mCallbackData;

DataReaderCallback::DataReaderCallback()
{

}
DataReaderCallback::~DataReaderCallback()
{

}

void DataReaderCallback::onGetData(String16 data)
{
    ALOGI("onGetData... %s", String8(data).string());
    mCallbackData = data;
}

sp<IDeviceMac> getService()
{
    sp<IServiceManager> sm = defaultServiceManager();
    if (sm == NULL)
    {
        ALOGE("Can not get service manager.");
    }

    sp<IBinder> binder = sm->getService(String16(SERVER_NAME));
    if (binder == NULL) {
         ALOGE("Can not get service %s.", SERVER_NAME);
    }

    sp<IDeviceMac> service = interface_cast<IDeviceMac>(binder);
    if (service == NULL)
    {
        ALOGE("Can not cast interface.");
    }

    return service;
}





int main(int argc, char** argv)
{
    sp<IDeviceMac> deviceMacService = getService();
    if (deviceMacService == NULL)
    {
        ALOGE("Device mac service is null. return error.");
        return -1;
    }

    deviceMacService->setBtMac(String8("1a:1b:1c:2a:2b:2c"));
    String8 btMac = deviceMacService->getBtMac();
    ALOGI("Get bt mac: %s", btMac.string());

    deviceMacService->setDataReaderCallback(new DataReaderCallback());
    
    deviceMacService->setBtMac(String8("33:33:33:33:33:33"));
    btMac = deviceMacService->getBtMac();
    ALOGI("Get bt mac: %s", btMac.string());

    if (mCallbackData) 
    {
        ALOGI("mCallbackData: %s", String8(mCallbackData).string());
    }

    return 0;
}

android/frameworks/av/services/mycore/Android.mk

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

LOCAL_SRC_FILES:= \
    DeviceMacService.cpp \

LOCAL_SHARED_LIBRARIES := \
    libcutils \
    libutils \
    liblog \
    libbinder \
	libmycore

LOCAL_MODULE:= libmycoreservice

include $(BUILD_SHARED_LIBRARY)


include $(CLEAR_VARS)
LOCAL_SRC_FILES:=               \
    main_devicemacservice.cpp

LOCAL_SHARED_LIBRARIES:= \
    libui \
    liblog \
    libutils \
    libbinder \
    libcutils \
    libmycoreservice \
    libmycore

LOCAL_MODULE:= mycoreservice
include $(BUILD_EXECUTABLE)



include $(CLEAR_VARS)
LOCAL_SRC_FILES:=               \
    DeviceMacClient.cpp \

LOCAL_SHARED_LIBRARIES:= \
    libui \
    liblog \
    libutils \
    libbinder \
    libcutils \
    libmycore

LOCAL_MODULE:= mycoreclient
include $(BUILD_EXECUTABLE)

四、开机启动servcie

android/device/xxx/yyy/yyy.mk

PRODUCT_PACKAGES += mycoreservice \
    mycoreclient

android/device/xxx/yyy/init.device.rc

service mycoreserver /system/bin/mycoreservice
     class main
     user root
     group root

五、测试结果

2022-01-08 15:55:32.099 6550-6550/? I/BpDeviceMac: Bp setBtMac
2022-01-08 15:55:32.100 2016-2016/? I/BpDeviceMac: Bn onTransact code: 1
2022-01-08 15:55:32.100 2016-2016/? I/DeviceMacService: Bn setBtMac, btMac: 1a:1b:1c:2a:2b:2c
2022-01-08 15:55:32.100 6550-6550/? I/BpDeviceMac: Bp getBtMac
2022-01-08 15:55:32.100 2016-2055/? I/BpDeviceMac: Bn onTransact code: 2
2022-01-08 15:55:32.100 2016-2055/? I/DeviceMacService: Bn getBtMac
2022-01-08 15:55:32.100 6550-6550/? I/DeviceMacDataReaderCallback: Get bt mac: 1a:1b:1c:2a:2b:2c
2022-01-08 15:55:32.100 6550-6550/? I/BpDeviceMac: Bp setDataReaderCallback
2022-01-08 15:55:32.101 2016-2016/? I/BpDeviceMac: Bn onTransact code: 3
2022-01-08 15:55:32.101 2016-2016/? I/DeviceMacService: Bn setDataReaderCallback
2022-01-08 15:55:32.101 6550-6550/? I/BpDeviceMac: Bp setBtMac
2022-01-08 15:55:32.101 2016-2055/? I/BpDeviceMac: Bn onTransact code: 1
2022-01-08 15:55:32.101 2016-2055/? I/DeviceMacService: Bn setBtMac, btMac: 33:33:33:33:33:33
2022-01-08 15:55:32.102 6550-6550/? I/BpDeviceMac: Bp getBtMac
2022-01-08 15:55:32.102 2016-2016/? I/BpDeviceMac: Bn onTransact code: 2
2022-01-08 15:55:32.102 2016-2016/? I/DeviceMacService: Bn getBtMac
2022-01-08 15:55:32.102 2016-2016/? I/DeviceMacService: Bn mCallback != NULL
2022-01-08 15:55:32.103 6550-6550/? I/DeviceMacBpDataReaderCallback: BnDataReaderCallback onTransact code: 1
2022-01-08 15:55:32.103 6550-6550/? I/DeviceMacDataReaderCallback: onGetData... callback data....
2022-01-08 15:55:32.103 6550-6550/? I/DeviceMacDataReaderCallback: Get bt mac: 33:33:33:33:33:33
2022-01-08 15:55:32.103 6550-6550/? I/DeviceMacDataReaderCallback: mCallbackData: callback data....

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值