Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/47405683
Here, I will use a small example of the form to help you explore the use of JNI, first of all, we must first build the NDK environment, please read the "Android--NDK Environment building" article.
First, to achieve
The function of this small example is to invoke C code through Java code in Android to implement the interaction between Java code and C code.
1. layout file
We first add a button control to the layout file Activity_main.xml, and set a click event for the button control, with the following code:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools " android:layout_width=" match_parent " android:layout_height=" Match_parent " android:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_ Horizontal_margin " android:paddingright=" @dimen/activity_horizontal_margin " android:paddingtop=" @dimen /activity_vertical_margin " tools:context=". Mainactivity "> <button android:layout_width=" wrap_content " android:layout_height=" Wrap_ Content " android:onclick=" click " android:text=" call C code "/></relativelayout>
2. Perfect class MainActivity1) define local methods
To implement a call to a JNI method, you first define a local method in Mainactivity, which is defined by the local method in Java with the native keyword.
The specific code is as follows:
Public native String HELLOFROMC ()
2) Generate with javah command, h header file
With the Javah command generation, h header file, if you want to configure the Java environment variables, here I do not say how to configure the environment variables, I believe a little knowledge of Java students know. We go through the cmd command line into the directory where the mainactivity package resides.
Such as:
then enter the command
Javah-encoding UTF-8 package name. Class Name
Where-encoding UTF-8 is the specified generated. h header file is encoded as UTF-8, the package name is the package where the class is located, the class name is the class name that contains the local method, and the class name does not have a. java suffix.
Such as:
At this point, a. h header file is generated under the current directory.
Such as:
3) Implement C code
The code generated in Com_lyz_hdk_helloworld_mainactivity.h is as follows:
/* Don't EDIT this file-it are machine generated */#include <jni.h>/* Header for class Com_lyz_hdk_helloworld_main Activity */#ifndef _included_com_lyz_hdk_helloworld_mainactivity#define _included_com_lyz_hdk_helloworld_ Mainactivity#ifdef __cplusplusextern "C" {#endif/* * Class: com_lyz_hdk_helloworld_mainactivity * Method: HELLOFROMC * Signature: () ljava/lang/string; */jniexport jstring jnicall JAVA_COM_LYZ_HDK_HELLOWORLD_MAINACTIVITY_HELLOFROMC (JNIENV *, jobject); #ifdef __ Cplusplus} #endif #endif
Create a new JNI directory at the root of your Android project, copy the Com_lyz_hdk_helloworld_mainactivity.h file to the JNI directory, and create a new hello.c file that introduces the required libraries.
As shown below:
#include <stdio.h> #include <jni.h> #include "com_lyz_hdk_helloworld_mainactivity.h"
Implement the Java_com_lyz_hdk_helloworld_mainactivity_hellofromc method in hello.c and return the corresponding string
The specific code is as follows:
Jniexport jstring jnicall JAVA_COM_LYZ_HDK_HELLOWORLD_MAINACTIVITY_HELLOFROMC (jnienv *env, Jobject obj) {char *str = " Hello from C "; jstring jstr = (**env). NEWSTRINGUTF (env, str); return jstr;}
HELLO.C complete code is as follows:
#include <stdio.h> #include <jni.h> #include "com_lyz_hdk_helloworld_mainactivity.h" Jniexport jstring Jnicall JAVA_COM_LYZ_HDK_HELLOWORLD_MAINACTIVITY_HELLOFROMC (jnienv *env, Jobject obj) {char *str = "Hello from c"; Jstring jstr = (**env). NEWSTRINGUTF (env, str); return jstr;}
4) Create android.mk under the JNI directory
This file is required for Android to implement JNI, and the file name fixed to android.mk cannot be changed. The contents of this file we can find the android-mk.html file in the NDK's Docs directory, open this file, locate the following code snippet, copy it to the Android.mk file, and note that there are no spaces for each line.
Local_path: = $ (call My-dir) include $ (clear_vars) local_module : = Hello-jni Local_src_files: = HELLO-JNI.C include $ (build_shared_library)
Its location in the file is as follows:
which
Local_path: = $ (call My-dir): directory where the current file exists
Call My-dir get the current directory of my Files
Include $ (clear_vars): Configuration information initialization
Local_module: = Hello-jni: Specifies the name of the executable file for the 2 binary value after compilation is complete
Local_src_files: = hello-jni.c: Specifies which C source files you want to compile
Include $ (build_shared_library): Compile into a dynamic link library file
Include $ (build_static_library): Compile into a static link library file
The file I want to compile is hello.c, so I want to generate the libhello.so so I modified the above configuration to the following code:
Local_path: = $ (call My-dir) include $ (clear_vars) local_module : = hellolocal_src_files: = Hello.cinclude $ (build_ Shared_library)
The above configuration is the content in Android.mk.
Such as:
At this point, the files in our project's JNI directory are as follows:
5) Compiling and generating so dynamic link library
We open the Cygwin and go to the project's JNI directory.
Such as:
Execute Command ndk-build
Such as:
The project project is refreshed and a. So dynamic link library is automatically generated in the Libs directory,
Such as:
6) Perfect Mainactivity
In the Mainactivity class, write a static block of code to load the. So dynamic link library, note that the. So file we generated here is libhello.so, and when we load the. So file, we just need to pass in hello.
The specific code is implemented as follows:
Load Static code block Static{system.loadlibrary ("Hello");}
The local method is mobilized in the button's click event, and the result is toast.
The specific code is as follows:
public void-click (View v) {Toast.maketext (this, "C code content is:" +HELLOFROMC (), Toast.length_short). Show ();
Mainactivity The overall code is as follows:
Package Com.lyz.hdk.helloworld;import Android.app.activity;import Android.os.bundle;import android.view.Menu; Import Android.view.view;import android.widget.toast;/** * Main access * @author Liuyazhuang * */public class mainactivity Extend s Activity {public native String HELLOFROMC ();//Load Static code block Static{system.loadlibrary ("Hello");} @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} public void-click (View v) {Toast.maketext (this, "C code content is:" +HELLOFROMC (), Toast.length_short). Show ();}}
Second, the Operation effect
Third, warm tips:
You can download the complete Android JNI sample source code to the link http://download.csdn.net/detail/l1028386804/8987847.
In this example, for the sake of the aspect, I write some text directly in the layout file and the related class, Everyone in the real project to write these words in the String.xml file, in the external reference to these resources, remember, this is the most basic development knowledge and specifications as an Android programmer, I am here just to facilitate directly written in the class and layout files.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
On the--jni of Android