AS 3.0-NDK配置与开发

Android Studio升级到3.0之后如何配置NDK开发环境并开发。

前言

Android Studio3.0及以上采用cmake来编译生成so文件。首先需要在SDK Tools中下载CMake和LLDB这两个组件,当然ndk也是必须的。

CMake:一款外部构建工具,可与Gradle搭配使用来构建原生库。如果您想用ndk-build(但AS3.0及以上已经不支持直接通过ndk-build进行编译了),则不需要此组件。
LLDB:一种调试程序,Android Studio使用它来调试原生代码。

环境配置及开发

1.首先在Android Studio中新建普通Android项目TestJNI。

2.然后在tetsjni/src/main/java/com.example.testjni目录下新建JNIDemo.java文件,内容如下——

package com.example.testjni;

public class JNIDemo {

    static{
        System.loadLibrary("Hello");  //将我们即将编写的native库命名为“Hello”
    }

    public static native String logString();  //声明我们要用到的native方法

}

3.然后分别在Android Studio的命令行界面(Terminal)上输入下图所示命令,依次生成文件JNIDemo.class和com_example_testjni_JNIDemo.h,如下图所示。

4.在main文件夹下新建jni文件夹,然后将com_example_testjni_JNIDemo.h放入该文件夹,并新建main.c文件(该文件就是c源码文件),将com_example_testjni_JNIDemo.h文件中的内容复制到main.c中,并完善函数内容(在这里我们简单的返回一个字符串)。

新建jni文件夹

jni文件夹内容

com_example_testjni_JNIDemo.h内容

main.c内容

5.然后在testjni目录下的配置文件build.gradle中加上以下配置内容,并在testjni目录下新建CMakeList.txt文件。

build.gradle更改如下——

CMakeLists.txt内容如下——

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.
#CMakeLists.txt
cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
  # 设置so文件名称.
   Hello                //这里需要改为JNIDemo.java中引用的so文件的名字

   # Sets the library as a shared library.
   SHARED
   # 设置这个so文件为共享.

   # Provides a relative path to your source file(s).
   # 设置这个so文件为共享.
   src/main/jni/main.c)        //这里需要设置成c源文件的路径

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
   log-lib

   # Specifies the name of the NDK library that
   # you want CMake to locate.
   log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
# 制定目标库.
Hello              //这里需要改为JNIDemo.java中引用的so文件的名字

# Links the target library to the log library
# included in the NDK.
${log-lib} )

6.最后别忘了在MainActivity.java中引用我们的native方法。最终整个项目结构及关键内容如下图所示。

运行打印日志如下图,开发成功。

最终生成的libHello.so在如下路径。

参考

Android Studio 3.0 利用cmake搭建jni环境(很详细哦)
Android Studio3.0 NDK配置与开发