Android 4.4.2 Dynamic addition of JNI library method Records (one JNI library layer)

Source: Internet
Author: User

Welcome to reprint, be sure to indicate the source. http://blog.csdn.net/wang_shuai_ww/article/details/44456755

This is the second method of adding JNI and services following the application layer development process record of the s5p4418 Android 4.4.2 Drive Layer HAL Layer service layer.

The previous approach was to add HAL and the service layer directly. Android in the API. The advantage of this approach is that the operating system has been developed, leaving the development of the app, Then we just need a Classes.jar file to be able to use our own Android system of the Hidden Pi (not in the official Android SDK API and the user to join the API), in the implementation of their own Android system platform can be directly convenient test. Of course, you can also make your own Android.jar file in the SDK's platforms corresponding Android version number. Replace the previous Android.jar. Then when you select the target Android version number, it is loaded with our own Android system API. To call our interfaces like android.os.xxx.


This article describes how to dynamically load JNI. As the name implies, it is when the APK executes to load the. So JNI library that we have written. This method is flexible, and it is very convenient to develop the transplant. There is no need to enter a folder in the source tree to do all kinds of tedious operations, only need to write a. c file that satisfies the requirements, compile and generate the corresponding. So file, and there is no special requirement for the location, I usually put it in the corresponding Board folder (/device/ Nexell/realarm).


It looks much more convenient than adding directly to the Android API. At least more concise, not so cumbersome, just the method in eclipse need to build a more class file, but also no big deal, O (∩_∩) O. For those who want to study fast. Join your own led operation for a friend. The method of this article is very suitable.


For dynamic JNI. First cite three blog posts, the address is http://blog.sina.com.cn/s/blog_4c451e0e0101339i.html, http://www.cnblogs.com/simonshi/archive/2011/ 01/25/1944910.html, http://blog.csdn.net/happy08god/article/details/11405607.

Friends are able to read more and see the similarities and differences they introduce.


This article is to participate in a number of posts after writing their own code on the Development Board test after the record written down, you can refer to the code to write their own program. Then compare the differences with other posts.


My source code folder is/device/nexell/realarm/led2, under which there are two files led2.c and android.mk. Their source code is as follows:

LED2.C:

#include <stdio.h> #include "jni.h" #include "JNIHelp.h" #include <assert.h>//Introduction Log header file # include <android /log.h>//Log Label # define TAG "Led_load_jni"//define Info Information # # Logi (...) __android_log_print (Android_log_info, TAG, __VA_ARGS__)//define DEBUG message # define LOGD (...) __android_log_print (Android_log_debug, TAG, __va_args__)//define error message # Define LOGE (...) __android_log_print (Android_log_error, TAG, __va_args__) <span style= "color: #ff0000;" > #define DEVICE_NAME "/dev/real_led" #define No_register</span><span style= "color: #ff0000;" > #ifndef no_register</span>static jint java_realarm_hardware_hardwarecontrol_ledsetstate (JNIEnv *env, Jobject thiz,jint lednum,jint ledstate) #elseJNIEXPORT jint jnicall java_realarm_hardware_hardwarecontrol_ledsetstate (JNIEnv *env, jobject thiz,jint lednum,jint ledstate) #endif {int fd = open (device_name, 0); if (fd = =-1) {LOGE ("LED Open err or "); return 1;} if (ledstate = = 0) logd ("led close success"), else if (ledstate = = 1) logd ("LEDOpen Success "), else {logd (" Led ledstate parameters ERROR. only 0 or 1. "); return 1;} Ledstate &= 0x01;ioctl (FD, ledstate, 0); close (FD); return 0;} <span style= "color: #ff0000;" > #ifndef no_register</span>static jninativemethod gmethods[] = {{"Ledsetstate", "(II) I", (void *) Java_realarm  _hardware_hardwarecontrol_ledsetstate},};    static int register_android_test_led (jnienv *env) {Jclass clazz;    static const char* Const KCLASSNAME = "Realarm/hardware/hardwarecontrol";    /* Look up the class */Clazz = (*env)->findclass (env, kclassname);    Clazz = Env->findclass (Env,kclassboa);        if (clazz = = NULL) {LOGE ("Can ' t find Class%s\n", Kclassname);    return-1; }/* Register all the methods */if ((*env)->registernatives (Env,clazz, Gmethods, sizeof (gmethods)/sizeof (Gmeth ODS[0]))! = JNI_OK)//if (Env->registernatives (Env,clazz, Gmethods, sizeof (gmethods)/sizeof (Gmethods[0]))! = Jni_o K) {LOGE ("Failed registering methodS for%s\n ", kclassname);    return-1; }/* Fill out the rest of the ID cache */return 0;} #endifjint jni_onload (javavm* vm, void* reserved) {<span style= "color: #ff0000;" > #ifndef no_register</span>jnienv *env = null;if ((*VM)->getenv (VM, (void**) &env, jni_version_1_4)! =  JNI_OK) {//if (vm->getenv (void * *) &env, jni_version_1_4)! = JNI_OK) {logi ("Error getenv\n");  return-1;  } assert (env! = NULL);  if (register_android_test_led (env) < 0) {printf ("register_android_test_led error.\n");  return-1;    } #endif/* Success--Return valid version number */logi ("/*****************realarm**********************/"); return jni_version_1_4;}

This code has done some processing after understanding its principle. This code can be used in two ways to finally refer to the Ledsetstate C + + implementation, detailed control, is the red part of the code above the macro.

1. Assume that the above macro is defined. Then the practical jni_onload function is the last word. return jni_version_1_4; Returns the JNI version number. There is no registration of Ledsetstate C + + implementation functions. So how does Android recognize it.

Assuming this is the case, Android will automatically search for the appropriate JNI method based on the Java layer's native defined in the class that the JNI references. Then this is required for the name of the function definition, the format of the Java_ package Name _ Class name _ Function name , Android app in the call Hardwarecontrol class inside the Ledsetstate method. will be actively matched to the corresponding JNI method.

One drawback of this approach is that CPU resources need to be consumed to match functions, resulting in inefficient execution. It's troublesome when the program is big.


2. It is therefore recommended to use a macro that does not define the red color above. In this case, when the library is called, the Ledsetstate function is passed (*env)->registernatives The register, and Java_realarm_hardware_hardwarecontrol_ Ledsetstate are bound together. And the APK calls the Ledsetstate method when the efficiency is much higher, do not have to take the initiative to match, because it has been explicitly told the operating system which function to call.


ANDROID.MK:

Local_path:= $ (call My-dir) include $ (clear_vars) Local_module_tags: = optionallocal_src_files: = Led2.clocal_shared_ LIBRARIES: = Libloglocal_c_includes + = $ (jni_h_include) local_ldlibs:=-l$ (sysroot)/usr/lib-lloglocal_prelink_module : = Falselocal_module_path: = $ (target_out_shared_libraries) Local_module: = Libledjniinclude $ (BUILD_SHARED_LIBRARY)

From the above code to know, I compiled the generated library named libledjni.so, note Local_module_path to use the path you see, that is, the/system/lib folder, when dynamically loaded. Also go to this folder to look for.


Okay, here's the JNI library, and we'll use the ADB push command to send it to the/system/lib folder on the Development Board. The next article will describe how to use it.


Android 4.4.2 Dynamic addition of JNI library method Records (one JNI library layer)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.