Android Studio JNI开发-CMake方式

Android Studio 开发jni所需插件:

如下图所示:

ndk-plugin.png

安装上图中红框标注的插件,可以很友好的进行c/c++代码编写
注:Android Studio的版本2.2及以上版本

开发过程

1、创建项目需要注意

选择include.png

注:include C++ support 打勾选择
C++支持选择.png

项目创建完成。
2、查看项目结构
c3.png

CMakeLists.txt:替代了之前的Android.mk和Application.mk

# 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.

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.
             #(1) 自定义so文件名称,可以自定义修改
             fm

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
            #(3)如果新增.cpp/.c文件时,需要手动在下面添加对应的文件全路径
             src/main/cpp/native-lib.cpp )

# 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.
                       # (2)自定义so文件名称,可以自定义修改
                       fm

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

如上面的文本所示:
(1)和(2)位置,如果需要自定义名称时,需要都修改;
(3)位置,如果新增.cpp/.c文件需要手动注册;
3、编译查看生成的.so文件
如下图所示:

c5.png

根据上图我们可以看出生成的.so文件的位置和Android Studio JNI开发-1中生成的位置路径不一致。
4、操作过程
创建java 的native方法

package fmblzf.cmakejni.ndk;

/**
 * Created by Administrator on 2017/5/25.
 */

public class CMakeNative {

    /**
     * 静态加载.so文件
     * 注意加载的so文件名称和build.gradle中的moduleName保持一致
     * 即没有lib前缀的文件名
     */
    static {
        System.loadLibrary("fm");
    }
    /**
     * 测试.so文件链接成功
     * @param str
     * @return
     */
    public static native String test(String str);
}

然后根据创建的类和方法去编写对应的jni代码,和Android Studio JNI开发-1中的操作完全一致,但是不同的是,在编写jni代码的时候友好的代码提示功能是非常有用和方便的。

c6.png

而且代码检查过程也忽略了爆红的情况(Android Studio JNI开发-1存在爆红,但是运行没有问题)。
5、运行
运行通过!!

源码下载

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容