记录用Android Studio创建NDK工程的步骤
创建APP工程.除了Acticity之外,添加一个NDK class
public class JniLib {
static {
System.loadLibrary("JniLib");
}
public static native String getNativeText();
}
通过以下命令生成jni的头文件
javah -d jni -classpath ~/Downloads/tool/sdk/platforms/android-19/android.jar:../../build/intermediates/classes/debug com.example.fredwang.jnitest.JniLib
头文件com_example_fredwang_jnitest_JniLib.h内容如下所示
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_example_fredwang_jnitest_JniLib */
#ifndef _Included_com_example_fredwang_jnitest_JniLib
#define _Included_com_example_fredwang_jnitest_JniLib
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_example_fredwang_jnitest_JniLib
* Method: getNativeText
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_example_fredwang_jnitest_JniLib_getNativeText
(JNIEnv *, jclass);
#ifdef __cplusplus
}
#endif
#endif
根据头文件创建对应实现的C文件JniLib.c
#include "com_example_fredwang_jnitest_JniLib.h"
//
// Created by fredwang on 16-6-8.
//
JNIEXPORT jstring JNICALL Java_com_example_fredwang_jnitest_JniLib_getNativeText
(JNIEnv *env, jclass obj)
{
return (*env) ->NewStringUTF(env, "This is JNI test!");
}
配置build.gradle
defaultConfig {
applicationId "com.example.fredwang.jnitest"
minSdkVersion 21
targetSdkVersion 23
versionCode 1
versionName "1.0"
ndk {
moduleName "JniLib"
}
}
配置local.properties
ndk.dir=/home/fredwang/Downloads/tool/NDK/android-ndk-r11b
最后在Activity中使用JNI
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textview);
textView.setText(JniLib.getNativeText());
}
}
通过build->make moudle编译即可运行