通过本篇教程,您将学习如何使用 Android Studio 轻松启动 Android NDK 项目开发。
开发环境
/android-sdk/ndk-bundle/
下Android Studio 通过 Google 开发的 experimental plugin
支持 native 开发,通过这个插件我们可以不用考虑配置麻烦的 Android.mk 等构建文件就可以进行开发,我们来将其添加到我们的项目中。
下面是 experimental 插件与 gradle 的版本对应表,详细查看官方文档,本教程我们将以 experimental plugin 0.7.3 为例
Plugin Version | Gradle Version |
---|---|
0.1.0 | 2.5 |
0.2.0 | 2.5 |
0.3.0-alpha3 | 2.6 |
0.4.0 | 2.8 |
0.6.0-alpha1 | 2.8 |
0.6.0-alpha5 | 2.10 |
0.7.0-alpha1 | 2.10 |
0.7.0 | 2.10 |
0.7.3 | 2.14.1 |
替换
classpath 'com.android.tools.build:gradle:2.2.0'
为
classpath 'com.android.tools.build:gradle-experimental:0.7.3'
替换
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.skyrin.hellojni"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
...
为
apply plugin: 'com.android.model.application' //<<<
model { //<<<
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.skyrin.hellojni"
minSdkVersion.apiLevel 15 //<<<
targetSdkVersion.apiLevel 25 //<<<
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles.add(file('proguard-android.txt')) //<<<
}
}
}
} //<<<
...
buildTypes {
...
}
//添加
ndk{
moduleName "hello-jni"
}
...
static {
System.loadLibrary("hello-jni");
}
public native String getStrFromJni();
...
#include <jni.h>
JNIEXPORT jstring JNICALL
Java_com_skyrin_hellojni_MainActivity_getStrFromJni(JNIEnv *env, jobject instance) {
// TODO
return (*env)->NewStringUTF(env, returnValue);
}
替换其返回值如下
return (*env)->NewStringUTF(env, "Hello Jni!");
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//调用jni代码
((TextView)findViewById(R.id.tv_jni)).setText(getStrFromJni());
}
static {
System.loadLibrary("hello-jni");
}
public native String getStrFromJni();
}
java
public native int add(int a,int b);
Jni
JNIEXPORT jint JNICALL
Java_com_skyrin_hellojni_MainActivity_add(JNIEnv *env, jobject instance, jint a, jint b) {
// TODO
return a+b;
}
调用
((TextView)findViewById(R.id.tv_jni)).setText(add(2,3)+"");