1. 建立Android Project File -> New -> Android Application Project 2. 定義調用C函數的java類,並產生(Eclipse中是自動編譯的)。 Java代碼: package lw.example.hellondk; public class HelloJni { public native String getStringFromJni(); public static native String getStringFromJniStatic(); static { System.loadLibrary("HelloNdk"); }} 3. 產生h檔案 在Project建立gen_h.bat檔案,輸入內容如下: javah -classpath bin\classes -d jni lw.example.hellondk.HelloJni@pause 運行該bat檔案後,會在jni目錄產生lw_example_hellondk_HelloJni.h檔案。 4. 添加Native支援 右擊Project -> Android Tools -> Add Native Support... 5. 附加Android Native C的h檔案 右擊project -> Properties,設定如下: 6. 在cpp檔案中實現函數。 #include "lw_example_hellondk_HelloJni.h" jstringJava_lw_example_hellondk_HelloJni_getStringFromJni(JNIEnv* env, jobject thiz){ return env->NewStringUTF("Hello JNI!");} jstringJava_lw_example_hellondk_HelloJni_getStringFromJniStatic(JNIEnv* env, jclass thiz){ return env->NewStringUTF("Hello JNI!(static)");} 7. 編譯so檔案 點擊工具列,編譯成功後,會產生so檔案。 8. 在Activity中添加測試代碼。 package lw.example.hellondk; import android.app.Activity;import android.widget.TextView;import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* Create a TextView and set its content. * the text is retrieved by calling a native * function. */ TextView tv = new TextView(this); tv.setText( HelloJni.getStringFromJniStatic() ); setContentView(tv); } }