首先新建一個工程
這個工程主要測試通過C程序返回一個字符串顯示在界面
最主要的部分已經標注。
- 第一步:JNI所對應的java類:
1 package com.sunxy.jnitest.jni; 2 3 /** 4 * Created by sunxy on 2016/7/28. 5 */ 6 7 public class SunxyNDk { 8 9 static { 10 System.loadLibrary("JniDemo"); 11 } 12 13 public static native String getStringFromNative(); 14 }
2. 第二步:編寫對應的C程序:
C程序主要由兩部分構成 .h文件和 .cpp文件
(1).h文件。定義方法。
1 // 2 // Created by sunxy on 2016/7/27. 3 // 4 /* DO NOT EDIT THIS FILE - it is machine generated */ 5 #include <jni.h> 6 /* Header for class com_sunxy_jnitest_jni_SunxyNDk */ 7 8 #ifndef _Included_com_sunxy_jnitest_jni_SunxyNDk 9 #define _Included_com_sunxy_jnitest_jni_SunxyNDk 10 #ifdef __cplusplus 11 extern "C" { 12 #endif 13 /* 14 * Class: com_sunxy_jnitest_jni_SunxyNDk 15 * Method: getStringFromNative 16 * Signature: (I)I 17 */ 18 19 JNIEXPORT jstring JNICALL Java_com_sunxy_jnitest_jni_SunxyNDk_getStringFromNative 20 (JNIEnv *env, jobject jObj); 21 #ifdef __cplusplus 22 } 23 #endif 24 #endif
(2).cpp文件。實現方法。
1 // 2 // Created by sunxy on 2016/7/28. 3 // 4 5 #include "sunxy.h" 6 7 8 JNIEXPORT jstring JNICALL Java_com_sunxy_jnitest_jni_SunxyNDk_getStringFromNative 9 (JNIEnv *env, jobject jObj){ 10 // return (*env)->NewStringUTF(env,"Hello From JNI!"); 11 12 jstring strRet = env->NewStringUTF("HelloWorld from Sunxy JNI !"); 13 return strRet; 14 }
3.第三步:在app文件下的 build.gradle文件中加入 moduleName "XXX" 設置生成的文件名
4. 第四步:在 gradle.properties 加入
android.useDeprecatedNdk=true
經過調試發現 .h 和 .cpp 這兩個文件可以只寫一個 .cpp 文件同樣可以實現相同的效果
1 // 2 // Created by sunxy on 2016/7/27. 3 // 4 /* DO NOT EDIT THIS FILE - it is machine generated */ 5 #include <jni.h> 6 /* Header for class com_sunxy_jnitest_jni_SunxyNDk */ 7 8 #ifndef _Included_com_sunxy_jnitest_jni_SunxyNDk 9 #define _Included_com_sunxy_jnitest_jni_SunxyNDk 10 #ifdef __cplusplus 11 extern "C" { 12 #endif 13 /* 14 * Class: com_sunxy_jnitest_jni_SunxyNDk 15 * Method: getStringFromNative 16 * Signature: (I)I 17 */ 18 19 JNIEXPORT jstring JNICALL Java_com_sunxy_jnitest_jni_SunxyNDk_getStringFromNative 20 (JNIEnv *env, jobject jObj){ 21 // return (*env)->NewStringUTF(env,"Hello From JNI!"); 22 23 jstring strRet = env->NewStringUTF("HelloWorld from Sunxy JNI !"); 24 return strRet; 25 } 26 27 #ifdef __cplusplus 28 } 29 #endif 30 #endif
最后運行程序就可以看結果了。
歡迎各位同志們批評、指正。