Android Studio 开发jni所需插件:
如下图所示:
安装上图中红框标注的插件,可以很友好的进行c/c++代码编写
注:Android Studio的版本2.2及以上版本
开发过程
1、创建项目需要注意
注:include C++ support 打勾选择
项目创建完成。
2、查看项目结构
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文件
如下图所示:
根据上图我们可以看出生成的.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代码的时候友好的代码提示功能是非常有用和方便的。
而且代码检查过程也忽略了爆红的情况(Android Studio JNI开发-1存在爆红,但是运行没有问题)。
5、运行
运行通过!!