This is a new project that I've created.
First step: Create a new Android project Jni_test
Step Two: Add local support for the project
Right-click on the project, select Android Tools-ADD Native Support, a dialog will pop up to let you enter the name of the library
This name you can make changes, you can also use the default, click Finish, you will find that the project more than a few folders, which is called JNI, here is where we write C code, the JNI folder default to produce 2 files, one is CPP, and one is the Mk file
Next you need to load the library file in Java code and declare the local method, as follows
Declaring a local method
Public native String Getstr ();
Jni_test is the file name of the library, the name that was entered in the popup dialog box, and the name of the so file generated after compiling the C file.
static {
System.loadlibrary ("Jni_test");
}
Note that if you need to use the local method directly in the activity, first remove the Extend activity code
Next we use the command to generate the header file.
Enter the project through the CD command, and then execute the full name of the class Javah-classpath bin/classes-d jni that uses native code
If the Javah command is unavailable, your Java environment variable is not configured to
After successful execution, you can find an extra. h file in the Jni folder
Of course you can also use Javah to produce header files.
The resulting header file name is very long, we can make a change, here I change to jni_test.h
Next we need to write the code in the CPP file based on our header file.
#include <jni.h>
#include <jni_test.h>
Jniexport jstring Jnicall Java_com_zhangyi_android_jnitest_mainactivity_getstr
(jnienv *env, Jobject obj) {
return Env->newstringutf ("Hello, I come from C");
}
Next, we need to modify the activity's code, because the Java code only declares the local code, does not call, in the layout file to add a text file, and then initialize it (do not write the code ha, can see this place is the people have a certain Android foundation) set the content for the text control for Getstr ();
Write the code, run it ~~~~~~~
Build a new Android project