Android Studio2.2.2 配置NDK
环境
- 主机:WIN 7
- 开发环境:Android Studio2.2.2
步骤
打开Tools->Android->SDK Manager->SDK Tools选中LLDB和NDK,点击确认,软件会自动安装NDK。
-
配置环境变量
- 增加一项:NDK_ROOT,如:C:\soft\adt-bundle-windows-x86-20130911\sdk\ndk-bundle
- 在path中增加%NDK_ROOT%
-
安装完记得重启
-
在main中新建文件夹jni
- 新建hello-jni.c
函数需按照规则命名:Java_包名类名方法名
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <string.h>
#include <jni.h>
/* This is a trivial JNI example where we use a native method
* to return a new VM String. See the corresponding Java source
* file located at:
*
* apps/samples/hello-jni/project/src/com/example/hellojni/HelloJni.java
*/
JNIEXPORT jstring JNICALL
Java_com_example_w_myapplication_MainActivity_stringFromJNI(JNIEnv *env, jobject instance) {
return (*env)->NewStringUTF(env, "Hello from JNI !");
}
- 新建Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := hello-jni.c
include $(BUILD_SHARED_LIBRARY)
- 在build.gradle中配置
配置好,make project即可生成.so文件在app\build\intermediates\ndk-build\debug\lib中。
增加语句:
externalNativeBuild {
ndkBuild {
path file("src\\main\\jni\\Android.mk")
}
}
完整的代码:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.3"
defaultConfig {
applicationId "com.example.w.myapplication"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
ndkBuild {
path file("src\\main\\jni\\Android.mk")
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'
}
- 在java层调用
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); System.out.println(stringFromJNI()); } public native String stringFromJNI(); static { System.loadLibrary("hello-jni"); } }