本文共 4486 字,大约阅读时间需要 14 分钟。
public class MainActivity extends Activity{ static { System.loadLibrary("JniTest"); } public native String getStringFromNative(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView txtView = (TextView) findViewById(R.id.txt); txtView.setText(getStringFromNative()); }}
Step: 3.javah生成c头文件
javah -d jni -classpath c:\Users\sodinochen\AppData\Local\Android\sdk\platforms\android-16\android.jar;..\..\build\intermediates\classes\debug lab.sodino.jnitest.MainActivity
最后的生成结果:
Step: 4.编辑c文件
/* DO NOT EDIT THIS FILE - it is machine generated */#include#include #ifndef LOG_TAG#define LOG_TAG "ANDROID_LAB"#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)#endif/* Header for class lab_sodino_jnitest_MainActivity */#ifndef _Included_lab_sodino_jnitest_MainActivity#define _Included_lab_sodino_jnitest_MainActivity#ifdef __cplusplusextern "C" {#endif/* * Class: lab_sodino_jnitest_MainActivity * Method: getStringFromNative * Signature: ()Ljava/lang/String; */JNIEXPORT jstring JNICALL Java_lab_sodino_jnitest_MainActivity_getStringFromNative (JNIEnv * env, jobject jObj){ LOGE("log string from ndk."); return (*env)->NewStringUTF(env,"Hello From JNI!"); }#ifdef __cplusplus}#endif#endif
Error:Execution failed for task ':app:compileDebugNdk'. > NDK not configured. Download the NDK from http://developer.android.com/tools/sdk/ndk/.Then add ndk.dir=path/to/ndk in local.properties. (On Windows, make sure you escape backslashes, e.g. C:\\ndk rather than C:\ndk)
好了,提示非常清楚了。那我们就进入下一步吧。
ndk { moduleName "JniTest" ldLibs "log", "z", "m" abiFilters "armeabi", "armeabi-v7a", "x86" }
Error:Execution failed for task ':app:compileDebugNdk'.> com.android.ide.common.internal.LoggedErrorException: Failed to run command: D:\Mission\adt-bundle-windows\ndk-r10b\ndk-build.cmd NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=C:\Users\sodinochen\AndroidstudioProjects\JniTest2\app\build\intermediates\ndk\debug\Android.mk APP_PLATFORM=android-21 NDK_OUT=C:\Users\sodinochen\AndroidstudioProjects\JniTest2\app\build\intermediates\ndk\debug\obj NDK_LIBS_OUT=C:\Users\sodinochen\AndroidstudioProjects\JniTest2\app\build\intermediates\ndk\debug\lib APP_ABI=armeabi,armeabi-v7a,x86Error Code: 2Output: make.exe: *** No rule to make target `C:\Users\sodinochen\AndroidstudioProjects\JniTest2\app\build\intermediates\ndk\debug\obj/local/armeabi/objs/JniTest/C_\Users\sodinochen\AndroidstudioProjects\JniTest2\app\src\main\jni', needed by `C:\Users\sodinochen\AndroidstudioProjects\JniTest2\app\build\intermediates\ndk\debug\obj/local/armeabi/objs/JniTest/C_\Users\sodinochen\AndroidstudioProjects\JniTest2\app\src\main\jni\main.o'. Stop.
Step: 6.安装运行
查看Log打印:
本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5371507.html,如需转载请自行联系原作者