前面对Binder的用途和通信过程涉及的代码进行了概述,这章主要用C来实现一个client和server,说再多不如代码体现的直接,下面的附上代码,代码都做了详细的注解,理解起来比较容易。
第一个程序是向Service_manager注册一个服务,编写一个test_server.c程序
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <linux/types.h>
#include <stdbool.h>
#include <string.h>
#include <private/android_filesystem_config.h>
#include "binder.h"
#include "test_server.h"
int svcmgr_publish(struct binder_state *bs, uint32_t target, const char *name, void *ptr)
{
int status;
unsigned iodata[512/4];
struct binder_io msg, reply;
bio_init(&msg, iodata, sizeof(iodata), 4);
bio_put_uint32(&msg, 0); // strict mode header
bio_put_string16_x(&msg, SVC_MGR_NAME);
bio_put_string16_x(&msg, name);
bio_put_obj(&msg, ptr);
/* 使用binder_call去访问ServiceManager 的 addService 函数 */
if (binder_call(bs, &msg, &reply, target, SVC_MGR_ADD_SERVICE))
return -1;
status = bio_get_uint32(&reply);
binder_done(bs, &msg, &reply);
return status;
}
void sayhello(void)
{
static int cnt = 0;
/* 简单的做个打印 */
fprintf(stderr, "say hello : %d\n", cnt++);
}
int sayhello_to(char *name)
{
static int cnt = 0;
/* 简单的做个打印 */
fprintf(stderr, "say hello to %s: %d\n", name, cnt++);
return 888;//验证是否client能收到