A quick tutorial to NDK development using new version of Android Studio 1.4

  1. 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.

  2. 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

  3. Make an declaration of the native method in the java code (main activity for example):

       native String StringFromJni();  
    
  4. Generate the JNI header file for the native method declared in step 3.
  5. 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);

  6. 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.

  7. 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());  
    
  8. Demo on github:
    Nimes.

19 Oct 2015