必要修改1:
build.gradle文件:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle-experimental:0.7.0' //修改了
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
必要修改2:
app\build.gradle文件:
apply plugin: 'com.android.model.application' //修改了
model{ //修改了
android {
compileSdkVersion 22
buildToolsVersion "24"
defaultConfig {
applicationId "myself.exercise.myndktest"
minSdkVersion.apiLevel 15 //修改了
targetSdkVersion.apiLevel 22//修改了
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
//proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
proguardFiles.add(file("proguard-rules.pro")) //修改了
}
}
ndk{
moduleName "lb" //增加的部分
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:design:22.2.1'
}
------------------------------------------------------------------------------------------------------------------------------------
方法一:
步驟1:
右鍵app->src->main: New->Folder->JNI Folder 不用勾選CheckBox
步驟2:
右鍵app->src->main->java->myself.exercise.myndktestt: New->Java Class->填寫Class名稱,這裏爲Load
內容爲
public class Load {
static {
System.loadLibrary("lb");
}
public native String getCLanguageString();
}
步驟3:
Build->Make Project
步驟4:
cd app\build\intermediates\classes\debug
javah -jni myself.exercise.myndktestt.Load //這裏Load第一個字母爲大寫
發現app\build\intermediates\classes\debug目錄下多出一個myself_exercise_myndktestt_Load.h
步驟5:
將myself_exercise_myndktestt_Load.h剪貼到app\src\main\jni目錄下
在該jni目錄右鍵 New->C/C++ Source File, 名稱隨意起.
如果爲cpp, 內容爲:
#include "myself_exercise_myndktestt_Load.h"
JNIEXPORT jstring JNICALL Java_myself_exercise_myndktestt_Load_getCLanguageString
(JNIEnv * env, jobject)
{
return env->NewStringUTF("This just a test for Android Studio NDK JNI developer!");
}
如果爲c, 內容爲:
#include "myself_exercise_myndktestt_Load.h"
JNIEXPORT jstring JNICALL Java_myself_exercise_myndktestt_Load_getCLanguageString
(JNIEnv * env, jobject)
{
return (*env)->NewStringUTF(env, "This just a test for Android Studio NDK JNI developer!");
}
步驟6:
在MainActivity.java中加入調用
Load ld = new Load();
Toast.makeText(getApplicationContext(), ld.getCLanguageString(), Toast.LENGTH_SHORT).show();