A quick tutorial to NDK development using new version of Android Studio 1.4
New a simple android application project in the AS and build the project. This will generate the class target objects for the java class. The generated objs will be located in:
app/build/intermediates/classes/debug.
Creat a jni directory in app/src/main/, so you will get:
src
├── androidTest
│ └── java
│ │ └── com
│ │ │ └── example
│ │ │ │ └── project_name
│ │ │ │ │ └── module_name
├── main
│ ├── java
│ │ └── com
│ │ │ └── example
│ │ │ │ └── project_name
│ │ │ │ │ └── module_name
│ ├── jni
│ └── res
│ │ ├── drawable
│ │ ├── layout
│ │ ├── menu
…
Make an declaration of the native method in the java code (main activity for example):
native String StringFromJni();
use javah command to generate the c/c++ header files
$JDKPath$\bin\javah -jni -d $ModuleFileDir$/src/main/jni $FileClass$
Note:
JDKPath - refers to your JDK installation directory.
-jni - means generate JNI-style header file (default).
-d - output directory, point to your jni directory just crated in step 2.
FileClass - com.example.georgeyan.nimes.Avignon. (the package name)
Now you can find the generated header file in your jni ditrctory (app/src/main/jni). The file name is com_package_name_projectname_module.h, containing:
JNIEXPORT jstring JNICALL Java_com_example_georgeyan_nimes_Avignon_StringFromJni(JNIEnv *, jobject);
Now create a c/c++ source file to implement it.
JNIEXPORT jstring JNICALL Java_com_example_georgeyan_nimes_Avignon_StringFromJni(JNIEnv * env, jobject ){
return (env)->NewStringUTF("HelloFromJni"); }
Two ways to compile the .so module:
[1] gradle: (if you want more about gradle, refer to this:gradle.)
add the following in the file app/build.gradle, in the defaultConfig bracket:
ndk {
moduleName "hello-jni"
}
you may need add `android.useDeprecatedNdk=true` in gradle.property
[2] Android.mk: build manually, not pratice using Android Studio.
The last thing is using the .so module in the java class.
static {
System.loadLibrary("hello-jni");
}
Example:
In the Oncreate function:
TextView text = (TextView)findViewById(R.id.hw);
text.setText(StringFromJni());
19 Oct 2015