废话不多说,上图上代码上步骤:
一.环境
1. 安装必要的工具:
CMake : NDK构建工具
LLDB : NDK调试工具
NDK : NDK开发工具
2.创建NDK项目
勾选下【c++ support】 然后一路next 到【Customize C++ Support】设置:
可以看到三个选项:
- C++ Standard:C++标准,选择【Toolchain Default】会使用默认的CMake配置。
- Exceptions Support:支持C++异常处理,标志为 -fexceptions。
- Runtime Type Information Support:支持运行时类型识别,标志为-frtti,程序能够使用基类的指针或引用来检查这些指针或引用所指的对象的实际派生类型。
在这里我们使用默认C++标准,不勾选下面的两个选项,点击【Finish】按钮进入下一个环节。
3.NDK项目
上面标注的就是区别于普通项目的地方,分别看下:
build.gradle配置:
可以看到build.gradle配置多了两个externalNativeBuild 配置项:
defaultConfig {
....
....
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
这里配置了CMake的命令参数,在创建项目时,如果勾选了【Exceptions Support】和【Runtime Type Information Supprot】选项,配置就变成了:
defaultConfig {
....
....
externalNativeBuild {
cmake {
cppFlags "-fexceptions -frtti"
}
}
}
更多的命令参数可查看官宣
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
外面的作用在于指定了CMake的构建脚本CMakeLists.txt的路径。
对CMakeLists.txt不太了解的稍后可以移步:CMakeLists.text详解
这里项目创建完成后,Android studio会自动给我们生成了一份配置好了的CMakeLists.text文件
# 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})
同时比普通的android项目多出了一个cpp文件夹和其路径下的native-lib.cpp源码文件。
源码定义了一个方法,方法名是通过Java_包名类名方法名 的方式命名的 native-lib.cpp,代码如下:
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_com_ing_ndklearn_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
其作用是返回一个字符串给Java层调用。
现在CmakeLists.txt 和 源码文件 AndroidStudio已经都帮我们准备好了,万事俱备,只欠东风,此刻你就是诸葛在世,羽扇纶巾,设坛作法,轻点一下【build】 -- 【Make project】稍等片刻~让风飞一会儿
当看到【build】--【intermediates】--【cmake】--【debug】--【obj】下
就看到东西南北so文件了...
so库文件生成了,如何调用,方法如下:
package com.ing.ndklearn;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
TextView tv = (TextView) findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
}
然后运行后看效果,这里就略了,效果就是页面显示“Hello from c++ ”。
题外话
这里的MainActivity 是默认生成的,即入口Activity,也是java层的调用类,如果你觉得怪,可以将其中jni的代码抽离出来,单独创建一个调用类,比如命名为NDKLibrary :
package com.ing.ndklearn;
/**
* Created by ing on 2019/7/9
*/
public class NDKLibrary {
static {
System.loadLibrary("native-lib");
}
public static native String stringFromJNI();
}
那么同时要修改下native-lib.cpp 将
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_com_ing_ndklearn_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
替换成
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_com_ing_ndklearn_NDKLibrary_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
重新Make Project下,生成新的so库。
此时,MainActivity作为调用方修改为如下
package com.ing.ndklearn;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
//
// // Used to load the 'native-lib' library on application startup.
// static {
// System.loadLibrary("native-lib");
// }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
TextView tv = (TextView) findViewById(R.id.sample_text);
tv.setText(NDKLibrary.stringFromJNI());
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
// public native String stringFromJNI();
}
运行后与之前的效果一致,页面显示“Hello from c++ ”。
总结一下整个过程
- Gradle 调用您的外部构建脚本
CMakeLists.txt
。 - CMake 按照构建脚本中的命令将 C++ 源文件
native-lib.cpp
编译到共享的对象库中,并命名为libnative-lib.so
,Gradle 随后会将其打包到 APK 中。 - 运行时,应用的
MainActivity
会使用System.loadLibrary()
加载原生库。现在,应用可以使用库的原生函数stringFromJNI()
。 -
MainActivity.onCreate()
调用stringFromJNI()
,这将返回“Hello from C++”并使用这些文字更新TextView
。
以上,就是利用AndroidStudio 默认的CMake方式构建NDK项目,虽然简单,但对于我们去认识理解NDK开发是很有用的。