開發(fā)環(huán)境:
Android studio2.0
ndk r10 64位
準(zhǔn)備工作:
NDK下載地址:http://www.cnblogs.com/yaotong/archive/2011/01/25/1943615.html
Android Studio下載地址:http://www.android-studio.org/
新建Android工程逊彭;
配置ndk路徑尸饺,F(xiàn)ile>Project Structure
工程目錄:
步驟一:
打開File>Settings>Tools>External Tools
點(diǎn)擊“加號”添加javah命令行,如圖:
步驟二:
創(chuàng)建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"http://生成的so名字
abiFilters"armeabi","armeabi-v7a","x86"http://輸出指定三種abi體系結(jié)構(gòu)下的so庫袜瞬。
}
}
debug{
ndk{
moduleName"jni-test"http://生成的so名字
abiFilters"armeabi","armeabi-v7a","x86"http://輸出指定三種abi體系結(jié)構(gòu)下的so庫怜俐。
}
}
}
makeproject,在app>build>intermediates>ndk下生成對應(yīng)的.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());
}
}
運(yùn)行。
報錯:
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"(具體原因自行g(shù)oogle)季稳。
報錯:
java.lang.UnsatisfiedLinkError
解決辦法:
在gradle中指定jniLibs路徑,示例如下(根據(jù)自己的實際路徑配置):
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']
}