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、運行
運行通過!!