向項目添加C/C++代碼分爲兩種狀況:html
1.1 下載NDK和構建工具android
1.2 建立支持C/C++的新項目菜單欄-File-new-new Project,新建項目bash
必定記得勾選箭頭指向的那個選項,否則建立出來的項目不會支持C/C++. 而後一路next
。app
這裏可能和咱們平時建立項目不同,可是這裏默認的就行了。點擊Finish
。最後建立的項目目錄結構ide
咱們發現箭頭所指的兩處就是相對於普通項目多了的兩個文件。 External Build Files
組用於存放CMake
或ndk-build
的構建腳本。 和Gradle
須要build.gradle
文件來指示如何構建應用同樣,CMake
和ndk-build
依照一個構建腳原本構建原生庫。 Android Studio建立了一個CMake
構建腳本CMakeLists.txt
(位於模塊的根目錄),用於指示編譯構建native-lib.cpp
。工具
如今看下native-lib.cpp
文件內容gradle
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_com_cyy_jnidemo_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
複製代碼
簡單的看出來他就是返回來一個字符串。ui
再看下CMakeLists.txt
文件的內容?this
# 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.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
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})
複製代碼
cmake_minimum_required
:生命要求的cmake最低版本。spa
add_library
:建立共享庫(把工程內的cpp文件都建立成共享庫文件,方便經過頭文件來調用) find_package
: 找到後面須要庫和頭文件的包 target_link_libraries
:把剛剛生成的${PROJECT_NAME}庫和所需的其它庫連接起來.
具體的含義仍是去百度吧。拿出2-3個小時,這地方相信確定就看的懂了。
那看下他在activity中咋用的呢?
就是這麼簡單。。。
如今運行下:
其實很簡單就幾步:
咱們也在app
模塊下建立個cpp包,而後在這個包下,也新建個native-lib.cpp
文件,能夠把以前他自動建立的內容複製進來,也能夠本身寫。
而後在app模塊下,也建立個CMakeLists.txt
文件。能夠把以前那個CMakeLists.txt
內容複製進來,可是路徑記得必定要改爲本身的。
最後在app
模塊下的build.gradle
中添加這兩個:
就ok了。