返回 登录
0

超级简单的Android Studio jni 实现(无需命令行)

1.配置Anroid Studio(这步是关键)

setting.png

javah.png

ndk-build.png

ndk-build clean.png

2.配置完成就可以使用javah 、ndk-build、ndk-build clean这三个命令了,那么在哪里使用这些命令,请看下图

tools.png

3.配置完成,我们开始新建工程MyNdk,然后新建jni目录

create jni.png

4.修改app下的build.gradle文件, 如下图

ndk{    
  moduleName "MyLibrary"
}
sourceSets.main{
    jni.srcDirs = []    
    jniLibs.srcDir "src/main/libs"
}

app build.gradle.png

5.修改MyNdk下的gradle.properties文件(如果没有此文件,自己新建一个),如下图

android.useDeprecatedNdk=true

MyNdk gradle.properties.png

6.新建MyNdk.java


public class MyNdk {
    static {
        System.loadLibrary("MyLibrary");    
}   
    public native String getString();
}

MyNdk.java.png

7.这步开始创建头文件,操作如下图(注意在MyNdk.java文件上点击右键)

create com_zhangyp_higo_myndk_MyNdk.h file.png

8.执行完成后jni目录下就创建了com_zhangyp_higo_myndk_MyNdk.h文件,然后我们在jni目录下编写 MyLibrary.cpp、Android.mk、Application.mk这三个文件,代码如下:
jni files.png

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目录上点击右键)

make ndk-build .png

10.得到so文件,如下图

so file.png

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!

MyLibrary.png

评论