Showing posts with label Android native service. Show all posts
Showing posts with label Android native service. Show all posts

Friday, May 22, 2009

How to write Android native service by C contntinue

Here is some thing I did; first, I copied biner.c to my private directory and used it as a library to access kernel binder driver. And then, I wrote my service to use the functions in binder.c to talk to service manager.
In order to talk with service manager, we need following things:
1. an unique id for the service we are going to build. It is a string16
2. add permission for our service to service manager.

For the point 1, I create an uint16 array like
uint16_t svcmgr_id16[] = {
'B','i','n','d','e','r','.','T','e','s','t','.','I','B','i','n',
'd','e','r','t','e','s','t'
};

for the point 2, I'm kind of lazy, I add a new item to the allowd[] in servicemanager. It looks like this:
{10001, "Binder.Test.IBindertest"}

Ok, lets get something real, we need to do following steps to make everything to work:
1. connect to the binder by calling binder_open function. The binder_open function creates a shared memory with /dev/binder. I copied service manager code to create a 128K shared memory.
2.create an io block through bio_init function to talk with service manager through binder. You need to provide a buff to bio_init. I use an integer array with size of 128
3. fill in the target (servicemanager) and source(Binder.Test.IBindertest) by calling bio_put_string16_x
4. call binder_call with command SVC_MGR_ADD_SERVICE. It is a blocking call. You need to provide a binder_io object for the result.
5. if binder_call returns 0, call binder_loop with a message handler callback function to process messages sent from service client.

The message processing callback function:
The prototype of the message processing callback functions is:
static int binder_handler(struct binder_state *bs,
struct binder_txn *txn,
struct binder_io *msg,
struct binder_io *reply)

In the callback function, we at least need to handle INTERFACE_TRANSACTION so that our service client can find our service.
switch(txn->code) {
case INTERFACE_TRANSACTION:
bio_put_string16(reply,svcmgr_id16);
break;
case :
default:
error handling.