My Android JNI Tutorial

My Android JNI Tutorial


Since I worked for my current employer, I found out my passion of writing was dropping down dramatically. My salary was raised and also got a promotion, but my ambition for the software looks have not evolved. So what is my favorite? coding and writing. I should keep that in my mind.

I reviewed what I did in the last few months, there are one thing suit my desire of writing. I wrote a JNI module to process the jbig compressed image, both decoding and encoding, actually I initially allocated this job to one of my former colleague, but it looks so sucks, then I have to refactor his code after his resignation, basically rewrote the code.

This is my first time to wrote JNI code with android-ndk, also my former jobs included a few JNI tasks, but it is in android system development not as an app developer.

Here are my experience and summary of JNI coding.

1. How to design JNI code?

Load the sharable library in static code in java part.
    static {
        System.loadLibrary("jbigkit");
    }

and write the native method with decoration statement - native.

public native byte[] encodeNative(Bitmap[] bitmaps)
 
In the JNI part, generate the header file with javah, or just write the 
according native methods by your hand with the following rules

 Jave + package_name + method_name 

2. How to invoke JNI code from Jave?


Obviously, we can invoke native method from java source code, and the implementation of the native method is in the C part.

3. How to build Jave object and operate it in JNI?


The best tutorial of JNI coding is jni.h header file, which is the best reference of JNI coding. And you have to understand the JNI data types and JNI type signatures, which is a little annoying, but fortunately there are explicitly explained in every JNI coding guard.

Following is a simple example, how to init a Java object and invoke its method, in this case, is a static method.
    jclass bmpCfgCls = (*env)->FindClass(env, "android/graphics/Bitmap$Config");
    jmethodID bmpCfgClsValueOf = (*env)->GetStaticMethodID(env, bmpCfgCls,                                                          "valueOf",
                                               "(Ljava/lang/String;)Landroid/graphics/Bitmap$Config;");
    jobject jBmpCfg = (*env)->CallStaticObjectMethod(env, bmpCfgCls,                                                            bmpCfgClsValueOf,
                                (*env)->NewStringUTF(env, "ARGB_8888"));

4. What NDK provided for us?

Nothing but the Bitmap and image related function by linking a few libraries.

5. How to write JNI CPP code?

Just put the jni methods into the magic block -- extern "C" { ... }



Comments

Popular posts from this blog

Bluedroid stack in android

How to setup a NAT server?

Network programming in elisp