owned this note
owned this note
Published
Linked with GitHub
# Android Native Development Kit (NDK)
###### tags: `android` `ndk`
## Android Studio
* This guide assume you to have a basic understanding of using Android Studio and Android development.
* Otherwise, please refer to the official tutorial (see [Meet Android Studio](https://developer.android.com/studio/intro/))
## Introduction to NDK
* NDK (Native Development Kit) : a toolset that lets you implement parts of your app in native code, using languages such as C and C++.
* Java Native Interface (JNI): The JNI is the interface via which the Java and C++ components talk to one another. For information about it, consult the [Java Native Interface Specification](https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html).
![](https://i.imgur.com/lVObq5J.png)
* ndk-build: The ndk-build script launches the build scripts at the heart of the NDK. These scripts:
* Automatically probe your development system and app project file to determine what to build.
* Generate binaries.
* Copy the binaries to your app's project path
* Java: From your Java source, the Android build process generates .dex (Dalvik Executable) files, which are what the Android OS runs in the Dalvik Virtual Machine (“DVM”). Even if your app contains no Java source code at all, the build process still generates a .dex executable file within which the native component runs.
* Native shared libraries: The NDK builds these libraries, or .so files, from your native source code.
* Native static libraries: The NDK can also build static libraries, or .a files, which you can link against other libraries.
* Application Binary Interface (ABI): The ABI defines exactly how your app's machine code is expected to interact with the system at runtime. The NDK builds .so files against these definitions. Different ABIs correspond to different architectures: The NDK includes ABI support for 32-bit ARM, AArch64, x86, and x86-64. For more information, see [ABI Management](https://developer.android.com/ndk/guides/abis).
* How a native project works ?
![](https://i.imgur.com/KJMVSAk.png)
* Java Native Library: Our java file that import native libraries and declare native functions.
* javah -jni : compile our java.class file to head file
* CMake : using CMake to compile C++ source code and header file to dynamic library (.so) and interact with Java file by JNI.
* Gradle : a custom build tool used to build android packages (apk files) by managing dependencies and providing custom build logic.
* reference : https://developer.android.com/ndk/guides/concepts
## NDK Project Example : NativeDemo
code download : http://git.jd.com/intern-svrdc10/SimpleAPP
## Install Dependencies
* Open Android SDK Manager in Android Studio
* in tool bar
![](https://i.imgur.com/dvml9lk.png =400x30)
* or in tools
![](https://i.imgur.com/oJQPXfw.png =300x400)
* Select CMake, LLDB, NDK
![](https://i.imgur.com/9528fWB.png =500x380)
* Press OK to start installing
* set system environment variable, add belows into PATH (optional)
```
> export ANDROID_SDK=/path/to/your/Android/sdk
> export ANDROID_NDK=/path/to/your/Android/sdk/ndk-bundle
> export PATH="$PATH:$ANDROID_SDK/tools:$ANDROID_SDK/platform-tools:$ANDROID_NDK"
```
### Create a Native Android Project
* Enable C++ support
![](https://i.imgur.com/PvdKTuh.png)
* Enable Exception and RTTI Support
![](https://i.imgur.com/jEyXOqe.png)
* Run the project
![](https://i.imgur.com/J8i7HWl.png =270x480)
### Native Source Code : native-lib.cpp
* /app/src/main/cpp/native-lib.cpp
```cpp=
#include <jni.h>
#include <string>
extern "C"
JNIEXPORT jstring JNICALL
Java_com_jd_nativedemo_Hello_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
```
* define your native function here.
* function named rule : Java\_{package name}\_{class name}\_{function name}
* JNIEnv : JNI interface pointer, it is related to caller's (in Java) thread, which helps us to us Java's function.
### CMakeList.txt
* define how you build your native code.
* basic setting
```
cmake_minimum_required(VERSION 3.4.1)
```
* build our target native code to libraray (SHARED $\to$ .so file, STATIC $\to$ .a file)
```
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 )
```
* using other libraries, like log-lib, the library provided by Android for printing log information.
```
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 )
```
* link our target native library to it dependencies.
```
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib} )
```
* after re-build the project, we can find our native-lib becomes a .so library in app/build/intermediates/cmake/debug/obj/{ABI}/
![](https://i.imgur.com/icimMmY.png)
### Add our Java Native Library class : Hello.java
* /app/src/main/java/com/xxx/nativedemo/Hello.java
* use our native function here.
* include our native library
* declare the native function. use the **native** keyword to indicate methods implemented as native code.
```java=
public class Hello {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public static native String stringFromJNI();
}
```
## Change NDK Version (optional)
* In some situation, you may want to using different version of NDK. Therefore, you need to know how to manually change the version.
* download the version you want in ([link](https://developer.android.com/ndk/downloads/))
* Unzip the folder.
* move all the files in android-ndk-rxxx/ to /your/sdk/path/ndk-bundle. (replace the original files)
* how to find your sdk path? open your sdk manager
![](https://i.imgur.com/2sKV4ab.png)
* Clean the project and rebuild
![](https://i.imgur.com/9wICwqs.png =300x330)
## Reference
* [Add C and C++ code to Your project](https://developer.android.com/studio/projects/add-native-code?hl=zh-us)
* [android Ndk学习笔记01之Hello World!](https://www.jianshu.com/p/e16834a6b939)
* [Android NDK开发(一) 使用CMake构建工具进行NDK开发](https://blog.csdn.net/kong_gu_you_lan/article/details/79091789)