用NDK调用第三方库遇到不少坑,总结一下。
1、添加JNI目录
参考:
http://www.cnblogs.com/lanqie/p/7442668.html
2、文件介绍:
其中:JniFactory 是包含native函数的类
libc4jniTest.a是第三方的库文件,非JNI规范
libc4jniTest.h 是对应的头文件
myjni-lib.c 是JNI规范的源文件,用于封装第三方库
上代码:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(activity_main); // Example of a call to a native method TextView tv = (TextView) findViewById(sample_text); tv.setText(JniFactory.cpp4jni("VBVBBVVBB")+"<<"); } }
public class JniFactory { public static native String cpp4jni(String str); static { System.loadLibrary("lmyjni-lib"); } }
Android.mk
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := libc4jniTest LOCAL_SRC_FILES := libc4jniTest.a include $(PREBUILT_STATIC_LIBRARY) include $(CLEAR_VARS) LOCAL_MODULE := lmyjni-lib LOCAL_SRC_FILES := myjni-lib.c LOCAL_STATIC_LIBRARIES := libc4jniTest include $(BUILD_SHARED_LIBRARY)
Application.mk
APP_ABI := armeabi armeabi-v7a
c4jniTest.h
#ifndef C4JNI_C4JNITEST_H #define C4JNI_C4JNITEST_H #include <string.h> char* c4jni_hello(char* string); #endif //C4JNI_C4JNITEST_H
myjni-lib.c
#include <jni.h> #include "c4jniTest.h" jstring Java_com_xh_jni_JniFactory_cpp4jni ( JNIEnv* env, jobject jobject,jstring x ) { return c4jni_hello(x); }
值得注意的有:
libc4jniTest.a 应该是交叉编译,应用于arm平台
步骤:
1.进入ndk目录 cd /opt/Java/android-ndk-r14b/build/tools
2. 安装工具到指定目录 ./make-standalone-toolchain.sh --platform=android-14 --install-dir=/opt/Java/arm-linux-androideabi/
3.编译c /opt/Java/arm-linux-androideabi/bin/arm-linux-androideabi-gcc -c c4jniTest.c
/opt/Java/arm-linux-androideabi/bin/arm-linux-androideabi-ar -cvr libc4jniTest.a c4jniTest.o
参考资料:http://blog.csdn.net/jiangxuchen/article/details/22883575