Mac 下 Android Studio 3.3 简单生成so文件


一. 配置环境安装 NDK


  2. Android Studio里安装。菜单栏 Tools ----> SDK Manger ----> SDK TOOLS .查找 到NDK下载。


二. 打开AndroidStudio 新建一个类,声明native方法。这个类是java与C/C++交互的中介,方法由java声明,由C/C++实现。

三.打开android studio终端,使用javac编译上述文件,生成class文件。

   1.终端 cd myJNI类所在的目录

   2.使用javac编译上述文件. javac 生成 myJNI.class 到项目里的java目录。然后在java目录使用 javah -jni 包名.类名 命令生成.h头文件 然后就能看到生成了一个h文件。 注意一定要在java层目录下输入命令,不然不会报错:找不到xxx类  

四. 新建一个jni文件夹,新建test.c,把.h里面的内容复制进去,并实现里面的函数。

1. 新建一个jni文件夹


3.把 ”javah -jni 包名.类名 命令生成.h头文件“ 生成的.文件放入jni文件夹下。并在test.c 实现它的方法。


LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)


APP_ABI := all

五. 使用CMake 创建CMakeLists.txt文件

 1.在Project 目录下,右键app,点击新建File文件,命名为CMakeLists.txt


# For more information about using CMake with Android Studio, read the
# documentation:

# Sets the minimum version of CMake required to build the native library.

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.
             MyJni #.so库名 可自定义

             # Sets the library as a shared library.

             # Provides a relative path to your source file(s).
             src/main/jni/test.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.
              # 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.
                       MyJni #.so库名 可自定义
                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

    3.右键app,点击Link C++ Project with Gradle,选择path:刚才的CMakeLists.txt,它会在 App build 生成相应的代码。


六. make projext 大功告成。

七. so文件在本项目里的使用。

    app Module 在Android 节点下:

sourceSets {
    main() {
        jniLibs.srcDirs = ['src/main/libs']
        jni.srcDirs = [] //屏蔽掉默认的jni编译生成过程