# 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 your native library. # This ensures that a certain set of CMake features is available to # your build.
# Specifies a library name, specifies whether the library is STATIC or # SHARED, and provides relative paths to the source code. You can # define multiple libraries by adding multiple add_library() commands, # and CMake builds them for you. When you build your app, Gradle # automatically packages shared libraries with your APK.
add_library( # Specifies the name of the library. bsdiff
# Sets the library as a shared library. SHARED
# Provides a relative path to your source file(s). bsdiff.c bspatch.c # 这里名字需要完全匹配,不能你是 cpp 类型文件,这里只写 .c 后缀;会有问题 diffpatch-lib.cpp ${bzip2} )
include_directories(src/main/cpp)
find_library( # Defines the name of the path variable that stores the # location of the NDK library. log-lib
# Specifies the name of the NDK library that # CMake needs to locate. log)
# Links your native library against one or more other native libraries. target_link_libraries( # Specifies the target library. bsdiff
# Links the log library to the target library. ${log-lib})
编写 Java 层工具类
此时进入 JNI 相关内容,编写 Java 工具类方便调用 Native 代码
1 2 3 4 5 6 7 8 9 10 11
public class BsdiffUtils { static { System.loadLibrary("bsdiff"); }
//生成差分包 public static native int diff(String oldFile, String newFile, String patchFile);
public static native int patch(String oldFile, String patchFile, String newFile); }
在 cpp 目录下 新建diffpatch-lib.cpp来实现底层 Native 方法。
在新版 AS 中(我的版本是 3.6.3),在刚新建的 cpp 文件里输入 jni,IDE 会有提示帮助你自动生成对应的 JNI 方法声明,如图所示: