1.配置Anroid Studio(这步是关键)
使用[command+,] 打开Preferences,选择External Tools,点击加号框如下图:
点击+号之后,打开Macros 配置宏命令界面,如下图:
2.配置完成就可以使用javah 、ndk-build、ndk-build clean这三个命令了,那么在哪里使用这些命令,请看下图
3.配置完成,我们开始新建工程MyNdk,然后新建jni目录
4.修改app下的build.gradle文件, 如下图
ndk{
moduleName "MyLibrary"
}
sourceSets.main{
jni.srcDirs = []
jniLibs.srcDir "src/main/libs"
}
5.修改MyNdk下的gradle.properties文件(如果没有此文件,自己新建一个),如下图
android.useDeprecatedNdk=true
6.新建MyNdk.java
public class MyNdk {
static {
System.loadLibrary("MyLibrary");
}
public native String getString();
}
7.这步开始创建头文件,操作如下图(注意在MyNdk.java文件上点击右键)
8.执行完成后jni目录下就创建了com_zhangyp_higo_myndk_MyNdk.h文件,然后我们在jni目录下编写 MyLibrary.cpp、Android.mk、Application.mk这三个文件,代码如下:
com_zhangyp_higo_myndk_MyNdk.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_zhangyp_higo_myndk_MyNdk */
#ifndef _Included_com_zhangyp_higo_myndk_MyNdk
#define _Included_com_zhangyp_higo_myndk_MyNdk
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_zhangyp_higo_myndk_MyNdk
* Method: getString
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_zhangyp_higo_myndk_MyNdk_getString
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
MyLibrary.cpp
#include "com_zhangyp_higo_myndk_MyNdk.h"
JNIEXPORT jstring JNICALL Java_com_zhangyp_higo_myndk_MyNdk_getString
(JNIEnv * env, jobject obj){
return (*env).NewStringUTF("This is mylibrary !!!");
}
Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := MyLibrary
LOCAL_SRC_FILES =: MyLibrary.cpp
include $(BUILD_SHARED_LIBRARY)
Application.mk
APP_MODULES := MyLibrary
APP_ABI := all
9.如何执行ndk-build,请看下图:(注意在jni目录上点击右键)
10.得到so文件,如下图
12.在MainActivity中调用,代码如下
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.tv);
tv.setText(new MyNdk().getString());
}
}
12.大功告成,可以运行了,oh yet!
此文转自:http://www.jianshu.com/p/e689d0196a17。