一般service的jni代码位于framework/base/service/jni/中,我们看看mokoid的ledservice是如何实现的:
framework/base/service/jni/com_mokoid_server_LedService.cpp
- static const JNINativeMethod gMethods[] = {
- { "_init", "()Z", (void *)mokoid_init },
- { "_set_on", "(I)Z", (void *)mokoid_setOn },
- { "_set_off", "(I)Z", (void *)mokoid_setOff },
- };
- int register_mokoid_server_LedService(JNIEnv* env) {
- static const char* const kClassName =
- "com/mokoid/server/LedService";
- jclass clazz;
- /* look up the class */
- clazz = env->FindClass(kClassName);
- if (clazz == NULL) {
- LOGE("Can't find class %s\n", kClassName);
- return -1;
- }
- /* register all the methods */
- if (env->RegisterNatives(clazz, gMethods,
- sizeof(gMethods) / sizeof(gMethods[0])) != JNI_OK)
- {
- LOGE("Failed registering methods for %s\n", kClassName);
- return -1;
- }
- /* fill out the rest of the ID cache */
- return 0;
- }
上面的函数register_mokoid_server_LedService会把以C/C++实现的接口注册为java可调用的接口,比如mokoid_init为C/C++代码,
而_init则位java可以使用的接口。这个函数会在JNI_OnLoad里面被调用。
再看看下面C/C++接口的具体实现:
- /** helper APIs */
- static inline int led_control_open(const struct hw_module_t* module,
- struct led_control_device_t** device) {
- return module->methods->open(module,
- LED_HARDWARE_MODULE_ID, (struct hw_device_t**)device);
- }
- static jboolean mokoid_init(JNIEnv *env, jclass clazz)
- {
- led_module_t* module;
- if (hw_get_module(LED_HARDWARE_MODULE_ID, (const hw_module_t**)&module) == 0) {
- LOGI("LedService JNI: LED Stub found.");
- if (led_control_open(&module->common, &sLedDevice) == 0) {
- LOGI("LedService JNI: Got Stub operations.");
- return 0;
- }
- }
- LOGE("LedService JNI: Get Stub operations failed.");
- return -1;
- }
- static jboolean mokoid_setOn(JNIEnv* env, jobject thiz, jint led)
- {
- LOGI("LedService JNI: mokoid_setOn() is invoked.");
- if (sLedDevice == NULL) {
- LOGI("LedService JNI: sLedDevice was not fetched correctly.");
- return -1;
- } else {
- return sLedDevice->set_on(sLedDevice, led);
- }
- }
- static jboolean mokoid_setOff(JNIEnv* env, jobject thiz, jint led)
- {
- LOGI("LedService JNI: mokoid_setOff() is invoked.");
- if (sLedDevice == NULL) {
- LOGI("LedService JNI: sLedDevice was not fetched correctly.");
- return -1;
- } else {
- return sLedDevice->set_off(sLedDevice, led);
- }
- }
从上面可以看到当init的时候,该jni service通过hw_get_module得到led的module,然后通过module->methods->open()打开该硬件,并且得到led硬件操作的
结构体(led_control_device_t)对象。
接着在mokoid_setOn和mokoid_setOff中分别利用led_control_device_t中的set_on和set_off进行相应的操作。
该jni service会被编译成libmokoid_runtime的动态链接库,提供给java service调用。