JNI does little error checking for better performance.
As a result, errors usually lead to a crash. A mode called CheckJNI
is offered by Android. In this mode, a set of JNI functions with extended checks are called instead of the normal JNI functions. This recipe discusses how to enable the CheckJNI mode to debug Android NDK applications.
The following steps create a sample Android project and enable the CheckJNI
mode:
CheckJNIDemo
. Set the package name as cookbook.chapter3
. Create an activity named CheckJNIDemoActivity
. Please refer to the Loading native libraries and registering native methods recipe of Chapter 2, Java Native Interface, if you want more detailed instructions.CheckJNIDemo
, select Android Tools | Add Native Support. A window appears; click on Finish to dismiss it.CheckJNIDemo.cpp
.CheckJNIDemoActivity.java
to the following:package cookbook.chapter3; import android.os.Bundle; import android.app.Activity; public class CheckJNIDemoActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_check_jnidemo); CheckJNIDemo(); } public native int[] CheckJNIDemo(); static { System.loadLibrary("CheckJNIDemo"); } }
CheckJNIDemo
project, and select Build Project.adb logcat -v time
" on a command-line console. Then, start the sample Android app on an Android device. The application will crash, and the logcat output will be displayed as follows:$ adb shell stop $ adb shell setprop dalvik.vm.checkjni true $ adb shell start
$ adb shell setprop debug.checkjni 1
The CheckJNI mode uses a set of JNI functions, which have more error checking than the default one. This makes it easier to find JNI programming bugs. The CheckJNI mode currently checks the following errors:
jarray
/jclass
/jobject
/jstring
to a JNI function. Passing NULL
to JNI function expecting a non-NULL argument./
" as in "java
/lang
/String
".jfieldIDs
or assigns jfieldIDs
from one type to another.DeleteGlobalRef
/DeleteLocalRef
on references of wrong types.0
, JNI_ABORT
, and JNI_COMMIT
to a release call.More error checking may be added to CheckJNI as Android evolves. Currently, the following checks are not supported: