开发环境:
Android studio2.0
ndk r10 64位
准备工作:
NDK下载地址:http://www.cnblogs.com/yaotong/archive/2011/01/25/1943615.html
Android Studio下载地址:http://www.android-studio.org/
新建Android工程;
配置ndk路径,File>Project Structure
工程目录:
步骤一:
打开File>Settings>Tools>External Tools
点击“加号”添加javah命令行,如图:
步骤二:
创建JniTest.class,代码如下
/**
* Created by h0nes1pr09rammer on 2016/8/16.
*/
public classJniTest {
static{
System.loadLibrary("jni-test");
}
public static nativeStringgetStrFromJni();
}
步骤三:
在main目录下新建jni目录,右键JniTest.class,选中NDK>javah,jni中生成“包名_JniTest.h”
步骤四:
编写jni-test.c,代码如下:
#include"com_ctwl_lzq_hellojnidemo_JniTest.h"
JNIEXPORT jstring JNICALL Java_com_ctwl_lzq_hellojnidemo_JniTest_getStrFromJni(JNIEnv * env,jobject obj){
char* cstr ="jni test";
return(*env)->NewStringUTF(env,cstr);
}
步骤五:
配置app下build.gradle,添加如下配置
buildTypes {
release {
...
ndk{
moduleName"jni-test"//生成的so名字
abiFilters"armeabi","armeabi-v7a","x86"//输出指定三种abi体系结构下的so库。
}
}
debug{
ndk{
moduleName"jni-test"//生成的so名字
abiFilters"armeabi","armeabi-v7a","x86"//输出指定三种abi体系结构下的so库。
}
}
}
makeproject,在app>build>intermediates>ndk下生成对应的.so文件。
步骤六:
修改MainActivity.class代码,如下:
public classMainActivityextendsAppCompatActivity {
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.tv);
JniTest jniTest =newJniTest();
textView.setText(jniTest.getStrFromJni());
}
}
运行。
报错:
Error:Execution failed for task ':app:compileDebugNdk'.
Error: NDK integration is deprecated in the current plugin. Consider trying the new experimental plugin. For details, see http://tools.android.com/tech-docs/new-build-system/gradle-experimental.
Set "android.useDeprecatedNdk=true" in gradle.properties to continue using the current NDK integration.
解决办法:
在gradle.properties中添加
android.useDeprecatedNdk=true
报错:
Error:Execution failed for task ':app:compileDebugNdk'.
com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: ... finished with non-zero exit value 2
解决办法:
在jni目录下新建空的.c文件,比如"empty.c"(具体原因自行google)。
报错:
java.lang.UnsatisfiedLinkError
解决办法:
在gradle中指定jniLibs路径,示例如下(根据自己的实际路径配置):
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
jniLibs.srcDirs = ['libs']
}