在Ubuntu为Android硬件抽象层(HAL)模块编写JNI方法提供Java访问硬件服务接口,在上两篇文章中,我们介绍了如何为Android系统的硬件编写驱动程序,包括如何在Linux内核空间实现内核驱动程序和在用户空间实现硬件抽象层接口。实现这两者的目的是为了向更上一层提供硬件访问接口,即为Android的Application Frameworks层提供硬件服务。我们知道,Android系统的应用程序是用Java语言编写的,而硬件驱动程序是用C语言来实现的,那么,Java接口如何去访问C接口呢?众所周知,Java提供了JNI方法调用,同样,在Android系统中,Java应用程序通过JNI来调用硬件抽象层接口。在这一篇文章中,我们将介绍如何为Android硬件抽象层接口编写JNI方法,以便使得上层的Java应用程序能够使用下层提供的硬件服务。


- #define
LOG_TAG “HelloService” - #include
“jni.h” - #include
“JNIHelp.h” - #include
“android_runtime/AndroidRuntime.h” - #include
- #include
- #include
- #include
- #include


- namespace
android - {
-
-
struct hello_device_t* hello_device = NULL; -
-
static void hello_setVal(JNIEnv* env, jobject clazz, jint value) { -
int val = value; -
LOGI(“Hello JNI: set value %d to device.”, val); -
if(!hello_device) { -
LOGI(“Hello JNI: device is not open.”); -
return; -
} -
-
hello_device->set_val(hello_device, val); -
} -
-
static jint hello_getVal(JNIEnv* env, jobject clazz) { -
int val = 0; -
if(!hello_device) { -
LOGI(“Hello JNI: device is not open.”); -
return val; -
} -
hello_device->get_val(hello_device, &val); -
-
LOGI(“Hello JNI: get value %d from device.”, val); -
-
return val; -
} -
-
static inline int hello_device_open(const hw_module_t* module, struct hello_device_t** device) { -
return module->methods->open(module, HELLO_HARDWARE_MODULE_ID, (struct hw_device_t**)device); -
} -
-
static jboolean hello_init(JNIEnv* env, jclass clazz) { -
hello_module_t* module; -
-
LOGI(“Hello JNI: initializing……”); -
if(hw_get_module(HELLO_HARDWARE_MODULE_ID, (const struct hw_module_t**)&module) == 0) { -
LOGI(“Hello JNI: hello Stub found.”); -
if(hello_device_open(&(module->common), &hello_device) == 0) { -
LOGI(“Hello JNI: hello device is open.”); -
return 0; -
} -
LOGE(“Hello JNI: failed to open hello device.”); -
return -1; -
} -
LOGE(“Hello JNI: failed to get hello stub module.”); -
return -1; -
} -
-
static const JNINativeMethod method_table[] = { -
{“init_native”, “()Z”, (void*)hello_init}, -
{“setVal_native”, “(I)V”, (void*)hello_setVal}, -
{“getVal_native”, “()I”, (void*)hello_getVal}, -
}; -
-
int register_android_server_HelloService(JNIEnv *env) { -
return jniRegisterNativeMethods (env, “com/android/server/HelloService”, method_table, NELEM(method_table)); -
} - };