使用 Binder 在 JAVA 与 C++ 之间传输数据

3 篇文章 0 订阅

JAVA 是客户端端,C++ 是服务端

 Java 端代码:

import android.view.InputChannel;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.ServiceManager;
import android.os.SystemProperties;

public boolean sendData(int cmd, Parcel data) throws Exception  {
    IBinder binder = null;
    final int MAX_WAIT = 9; //最多获取service 10次
    int index = 0;
    //SystemProperties.set("ctl.start", "tsp_auto_service");
    do {
        Log.i("---LHC---", "get service : chinatsp.autoaction");
        binder = ServiceManager.getService("chinatsp.autoaction");
        if (null == binder){
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }while ((null == binder) && ((index++) < MAX_WAIT));
    if (null == binder){
        Log.i("---LHC---", "get service of autoaction failed");
        data.recycle();
        //SystemProperties.set("ctl.stop", "tsp_auto_service");
        return false;
    }
    Parcel reply = Parcel.obtain();
    int result = -1;
    try {
        Log.i("---LHC---", "cmd = " + cmd);
        binder.transact(cmd, data, reply, 0);
        result = reply.readInt();
    } catch (Exception e) {
        Log.i("---LHC---", "send cmd to autoaction service : error");
    }
    data.recycle();
    reply.recycle();
    //SystemProperties.set("ctl.stop", "tsp_auto_service");
    return result == 0;
}

调用 JAVA 端代码,例:传输 InputChannel

private final static int SEND_INPUTCHANNEL = 0x1;

Parcel parcel = Parcel.obtain();
InputChannel mInputChannel = new InputChannel();
mInputChannel.writeToParcel(parcel, 0);
parcel.setDataPosition(0);

sendData(SEND_INPUTCHANNEL, parcel);

C++ 端代码 RecParacel.h

#ifndef _DELETE_FILE
#define _DELETE_FILE

#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <utils/threads.h>
#include <stdio.h>
#include <stdbool.h>
#include <android/log.h>

namespace android{
	class RecParacel: public BBinder{
	public:
		static int instantiate();
		DeleteFile();
		virtual ~DeleteFile();
		virtual status_t onTransact(uint32_t, const Parcel&, Parcel*, uint32_t);
	};
}//namespace

#endif

C++ 端代码 RecParacel.cpp

#include "RecParacel.h"
#include <binder/IServiceManager.h>
#include <binder/IPCThreadState.h>
#include <cutils/log.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "../utils/log.h"

#define SEND_INPUTCHANNEL 0x01
#define SERVICE_NAME "chinatsp.autoaction"

int dealRecParacels(const char* path){
	char* cmd = (char*) malloc(16 + strlen(path));
	memset(cmd, 0, sizeof(cmd));
	sprintf(cmd, "rm -rf %s", path);
	int result = system(cmd);
	free(cmd);
	return result;
}

namespace android{
RecParacel::RecParacel(){
}
RecParacel::~RecParacel(){

}
int RecParacel::instantiate(){
	int r = defaultServiceManager()->addService(String16(SERVICE_NAME), new RecParacel());
	return r;
}

status_t RecParacel::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
		uint32_t flags) {
	switch (code) {
	case SEND_INPUTCHANNEL:{
//		int keep = data.readInt32();
        int32_t intI = data.readInt32();
        std::string name = data.readCString();
        sp<IBinder> token = data.readStrongBinder();
        android::base::unique_fd rawFd;
        status_t fdResult = data.readUniqueFileDescriptor(&rawFd);

        LOGMINAI("RecParacel::onTransact read inputChannel finish intI:%d name:%s fdResult:%d\n"
                 ,intI, name.c_str(), fdResult);

		system("sync");
		return 0;
	}
	break;
	default: {
			return BBinder::onTransact(code, data, reply, flags);
		}
			break;
	}
}

}//namespace

调用C++ 端代码 

#include <pthread.h>

{

  pthread_t thid;
  LOGMINAE("---LHC---newthid = pthread_self();main thread ,ID is %ld\n",pthread_self());
  if(pthread_create(&thid, NULL, &say_hello, NULL) != 0) {
    LOGMINAE("---LHC---newthid = pthread_self();thread creation failed\n");
  }
  LOGMINAE("---LHC---thread creation success!\n");

}


void *say_hello(void* args)
{
  pthread_t newthid;
  newthid = pthread_self();
  LOGMINAE("---LHC---this is a new thread, thread ID = %ld\n", newthid);
  sp<ProcessState> proc(ProcessState::self());
  sp<IServiceManager> sm = defaultServiceManager(); //取得 ServiceManager
  android::DeleteFile::instantiate();
  ProcessState::self()->startThreadPool(); //启动缓冲池
  IPCThreadState::self()->joinThreadPool(); //这里是把服务添加到 Binder闭合循环进程中
  LOGMINAE("say_hello\n");
  return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值