Saturday, June 6, 2009

How to access a C native service from Java side in Android

I have mentioned how to add a native service by C. Now, it is the time to discuss about the client implementation. A client, in this document is a activity. It can talk to the native service to instruct the native service to do something for it.
It seems that there has no way to do this with a standard method supported by Android SDK. So I went to another route. I built a platform library. The platform library talks to the servicemanager.java to access the binder hence the native service. The code is very simple. To find out how to build and use a platform library, you can check out the android source code and take a look at the README.txt in the directory development/samples/PlatformLibrary

package com.servicelib.mybinder;

import android.util.Config;
import android.util.Log;
import android.os.ServiceManager;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;


public final class MyBinderLibrary {


private static IBinder mServiceManager = null;

public MyBinderLibrary() {

}

public static IBinder AttachService(String name) {
if (mServiceManager == null) {
mServiceManager = ServiceManager.getService(name);
}

return mServiceManager;
}

public static int SendKillSignal() throws RemoteException
{
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
int result;
try{
data.writeInterfaceToken(mServiceManager.getInterfaceDescriptor());
mServiceManager.transact(TRANSACTION_sendKill,data,reply,0);
reply.readException();
result = reply.readInt();
}
finally{
reply.recycle();
data.recycle();
}

return result;
}
static final int TRANSACTION_sendKill = (IBinder.FIRST_CALL_TRANSACTION+0);
}


So, in your activity, call the methods in this class directly. So that you can talk to the native service. You need to make sure the name of the service is correct.

1 comment:

  1. The android.os.ServiceManager is not availabe now, how do you handle this?

    ReplyDelete