Android-ndk開發(一)
一、開發環境:
1、Windows 10系統電腦
2、Android Studio 3.2.1
3、Jdk1.8
4、Android ndk 16 (開發JNI必備工具,就是模拟其他平台特性類編譯代碼的工具)
image.png
image.png
二、建立項目,勾選支援C++選項,項目會自動建構支援原生開發,現在的版本使用Cmake建構,使用起來非常友善了。
image.png
帶有C/C++的項目目錄多了CPP檔案夾(存放C/C++代碼的)和CMakeLists.txt檔案(編譯C/C++程式的)
image.png
# 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.
#配置so庫資訊
add_library( # Sets the name of the library.
# 生成的so庫名稱,此處生成的so檔案名稱是libnative-lib.so
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
# 資源檔案,可以多個,
# 資源路徑是相對路徑,相對于本CMakeLists.txt所在目錄
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.
# 目标庫
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib})
image.png
image.png
App目錄下的build.gradle檔案會新添配置Cmake環境的代碼
image.png
如果想要編譯不同平台的so檔案需要添加一下代碼
ndk{
abiFilters "armeabi", "armeabi-v7a"//,"x86"
}
image.png
生成so檔案的目錄
image.png
三、建立JNI方法。上面是建立項目勾選C/C++自動生成的一些配置和代碼,下面我們自己定義一個Java本地接口(Jni)方法,在native-lib.cpp中執行邏輯。
1、在MainActivity中建立getJNIString()的JNI方法;
image.png
目前狀态方法狀态還是紅色,沒有聲明,現在我們根據提示在native-lib.cpp的類中建立。
image.png
image.png
我們便可以在這個方法執行我們想要處理的一些邏輯,這裡需要使用JNI和C/C++文法。(僅供新手參考,正在學習中)