NDK入门

What is the NDK?

什么是NDK？

The Android NDK is a toolset that lets you embed components that make use of native code in your Android applications.

Android NDK是一个工具集，通过它，可以在你的Android应用中嵌入原生代码。

Android applications run in the Dalvik virtual machine. The NDK allows you to implement parts of your applications using native-code languages such as C and C++. This can provide benefits to certain classes of applications, in the form of reuse of existing
code and in some cases increased speed.

A set of tools and build files used to generate native code libraries from C and C++ sources

A way to embed the corresponding native libraries into an application package file (.apk) that can be deployed on Android devices

A set of native system headers and libraries that will be supported in all future versions of the Android platform, starting from Android 1.5. Applications that use native activities must be run on Android 2.3 or later.

Documentation, samples, and tutorials

NDK提供了：

一系列的工具和build文件来从C、C++的源码生成原生代码库

在应用包文件中嵌入相关的原生库，它可被部署到Android设备上

原生系统头文件和库的集

文档、实例、手册

The latest release of the NDK supports the following instruction sets:

ARMv5TE (including Thumb-1 instructions)

ARMv7-A (including Thumb-2 and VFPv3-D16 instructions, with optional support for NEON/VFPv3-D32 instructions)

x86 instructions (see CPU-ARCH-ABIS.HTML for more information)

ARMv5TE machine code will run on all ARM-based Android devices. ARMv7-A will run only on devices such as the Verizon Droid or Google Nexus One that have a compatible CPU. The main difference between the two instruction sets is that ARMv7-A supports hardware
FPU, Thumb-2, and NEON instructions. You can target either or both of the instruction sets — ARMv5TE is the default, but switching to ARMv7-A is as easy as adding a single line to the application's Application.mk file,
without needing to change anything else in the file. You can also build for both architectures at the same time and have everything stored in the final .apk. Complete information is provided in the CPU-ARCH-ABIS.HTML
in the NDK package.

The NDK provides stable headers for libc (the C library), libm (the Math library), OpenGL ES (3D graphics library), the JNI interface, and other libraries, as listed in the Development
Tools section.

When to Develop in Native Code

The NDK will not benefit most applications. As a developer, you need to balance its benefits against its drawbacks; notably, using native code does not result in an automatic performance increase, but always increases application complexity. In general, you
should only use native code if it is essential to your application, not just because you prefer to program in C/C++.

Typical good candidates for the NDK are self-contained, CPU-intensive operations that don't allocate much memory, such as signal processing, physics simulation, and so on. Simply re-coding a method to run in C usually does not result in a large performance
increase. When examining whether or not you should develop in native code, think about your requirements and see if the Android framework APIs provide the functionality that you need. The NDK can, however, can be an effective way to reuse a large corpus of
existing C/C++ code.

The Android framework provides two ways to use native code:

Write your application using the Android framework and use JNI to access the APIs provided by the Android NDK. This technique allows you to take advantage of the convenience of the Android framework, but still allows you to write native code when necessary.
You can install applications that use native code through the JNI on devices that run Android 1.5 or later.

Write a native activity, which allows you to implement the lifecycle callbacks in native code. The Android SDK provides the NativeActivity class,
which is a convenience class that notifies your native code of any activity lifecycle callbacks (onCreate(), onPause(), onResume(),
etc). You can implement the callbacks in your native code to handle these events when they occur. Applications that use native activities must be run on Android 2.3 (API Level 9) or later.

You cannot access features such as Services and Content Providers natively, so if you want to use them or any other framework API, you can still write JNI code to do so.

You can find the documentation in the <ndk>/docs/ directory.
In particular, please read the OVERVIEW.HTML document completely, so that you understand the intent of the NDK and how to use it.

Here's the general outline of how you work with the NDK tools:

Place your native sources under <project>/jni/...

Create <project>/jni/Android.mk to describe your native sources to the NDK build system

Optional: Create <project>/jni/Application.mk.

Build your native code by running the 'ndk-build' script from your project's directory. It is located in the top-level NDK directory:

cd <project>
<ndk>/ndk-build

The build tools copy the stripped, shared libraries needed by your application to the proper location in the application's project directory.

Finally, compile your application using the SDK tools in the usual way. The SDK build tools will package the shared libraries in the application's deployable .apk file.

Sample applications

The NDK includes sample applications that illustrate how to use native code in your Android applications:

hello-jni — a simple application that loads a string from a native method implemented in a shared library and then displays it in the application UI.

two-libs — a simple application that loads a shared library dynamically and calls a native method provided by the library. In this case, the method is implemented in a static library imported by the shared
library.

san-angeles — a simple application that renders 3D graphics through the native OpenGL ES APIs, while managing activity lifecycle with a GLSurfaceView object.

hello-neon — a simple application that shows how to use the cpufeatures library to check CPU capabilities at runtime, then use NEON intrinsics
if supported by the CPU. Specifically, the application implements two versions of a tiny benchmark for a FIR filter loop, a C version and a NEON-optimized version for devices that support it.

bitmap-plasma — a simple application that demonstrates how to access the pixel buffers of Android Bitmap objects
from native code, and uses this to generate an old-school "plasma" effect.

native-activity — a simple application that demonstrates how to use the native-app-glue static library to create a native activity

native-plasma — a version of bitmap-plasma implemented with a native activity.

For each sample, the NDK includes the corresponding C source code and the necessary Android.mk and Application.mk files. There are located under <ndk>/samples/<name>/ and their source code can be found
under <ndk>/samples/<name>/jni/.

You can build the shared libraries for the sample apps by going into <ndk>/samples/<name>/ then calling the ndk-build command. The generated shared
libraries will be located under<ndk>/samples/<name>/libs/armeabi/ for (ARMv5TE machine code) and/or <ndk>/samples/<name>/libs/armeabi-v7a/ for
(ARMv7 machine code).

Next, build the sample Android applications that use the shared libraries:

If you are developing in Eclipse with ADT, use the New Project Wizard to create a new Android project for each sample, using the "Import from Existing Source" option and importing the source from <ndk>/apps/<app_name>/project/.
Then, set up an AVD, if necessary, and build/run the application in the emulator.

If you are developing with Ant, use the android tool to create the build file for each of the sample projects at <ndk>/apps/<app_name>/project/.
Then set up an AVD, if necessary, build your project in the usual way, and run it in the emulator.

Exploring the hello-jni Sample

The hello-jni sample is a simple demonstration on how to use JNI from an Android application. The HelloJni activity receives a string from a simple C function and displays it in a TextView.

The main components of the sample include:

The familiar basic structure of an Android application (an AndroidManifest.xml file, a src/ and res directories,
and a main activity)

A jni/ directory that includes the implemented source file for the native code as well as the Android.mk file

A tests/ directory that contains unit test code.

Create a new project in Eclipse from the existing sample source or use the android tool to update the project so it generates a build.xml file that you can use to build the sample.

In Eclipse:

Click File > New Android Project...

Select the Create project from existing source radio button.

Select any API level above Android 1.5.

In the Location field, click Browse... and select the <ndk-root>/samples/hello-jni directory.

Click Finish.

On the command line:

Change to the <ndk-root>/samples/hello-jni directory.

Run the following command to generate a build.xml file:

android update project -p . -s

Compile the native code using the ndk-build command.

cd <ndk-root>/samples/hello-jni
<ndk_root>/ndk-build

Build and install the application as you would a normal Android application. If you are using Eclipse, run the application to build and install it on a device. If you are using Ant, run the following commands from the project directory:

ant debug
adb install bin/HelloJni-debug.apk

When you run the application on the device, the string Hello JNI should appear on your device. You can explore the rest of the samples that are located in the <ndk-root>/samples directory
for more examples on how to use the JNI.

Exploring the native-activity Sample Application

The native-activity sample provided with the Android NDK demonstrates how to use the android_native_app_glue static library. This static library makes creating a native activity easier by providing you with an implementation that handles your callbacks in another
thread, so you do not have to worry about them blocking your main UI thread. The main parts of the sample are described below:

The familiar basic structure of an Android application (an AndroidManifest.xml file, a src/ and res directories).
The AndroidManifest.xml declares that the application is native and specifies the .so file of the native activity. See NativeActivity for
the source or see the <ndk_root>/platforms/samples/native-activity/AndroidManifest.xml file.

A jni/ directory contains the native activity, main.c, which uses the android_native_app_glue.h interface to implement the activity. The Android.mk
that describes the native module to the build system also exists here.

To build this sample application:

Create a new project in Eclipse from the existing sample source or use the android tool to update the project so it generates a build.xml file that you can use to build the sample.

In Eclipse:

Click File > New Android Project...

Select the Create project from existing source radio button.

Select any API level above Android 2.3.

In the Location field, click Browse... and select the <ndk-root>/samples/native-activity directory.

Build and install the application as you would a normal Android application. If you are using Eclipse, run the application to build and install it on a device. If you are using Ant, run the following commands in the project directory, then run the application
on the device:

ant debug
adb install bin/NativeActivity-debug.apk

Documentation

The NDK package includes a set of documentation that describes the capabilities of the NDK and how to use it to create shared libraries for your Android applications. In this release, the documentation is provided only in the downloadable NDK package. You can
find the documentation in the <ndk>/docs/ directory. Included are these files:

INSTALL.HTML — describes how to install the NDK and configure it for your host system

OVERVIEW.HTML — provides an overview of the NDK capabilities and usage

ANDROID-MK.HTML — describes the use of the Android.mk file, which defines the native sources you want to compile

APPLICATION-MK.HTML — describes the use of the Application.mk file, which describes the native sources required by your Android application

CPLUSPLUS-SUPPORT.HTML — describes the C++ support provided in the Android NDK

CPU-ARCH-ABIS.HTML — a description of supported CPU architectures and how to target them.

CPU-FEATURES.HTML — a description of the cpufeatures static library that lets your application code detect the target device's CPU family and the optional features at runtime.

CPU-ARM-NEON.HTML — a description of how to build with optional ARM NEON / VFPv3-D32 instructions.

CHANGES.HTML — a complete list of changes to the NDK across all releases.

DEVELOPMENT.HTML — describes how to modify the NDK and generate release packages for it

HOWTO.HTML — information about common tasks associated with NDK development

IMPORT-MODULE.HTML — describes how to share and reuse modules

LICENSES.HTML — information about the various open source licenses that govern the Android NDK

NATIVE-ACTIVITY.HTML — describes how to implement native activities

NDK-BUILD.HTML — describes the usage of the ndk-build script

NDK-GDB.HTML — describes how to use the native code debugger

PREBUILTS.HTML — information about how shared and static prebuilt libraries work

STANDALONE-TOOLCHAIN.HTML — describes how to use Android NDK toolchain as a standalone compiler (still in beta).

SYSTEM-ISSUES.HTML — known issues in the Android system images that you should be aware of, if you are developing using the NDK.

STABLE-APIS.HTML — a complete list of the stable APIs exposed by headers in the NDK.

Additionally, the package includes detailed information about the "bionic" C library provided with the Android platform that you should be aware of, if you are developing using the NDK. You can find the documentation in the <ndk>/docs/system/libc/ directory:

OVERVIEW.HTML — provides an overview of the "bionic" C library and the features it offers.

Development tools

The NDK includes a set of cross-toolchains (compilers, linkers, etc..) that can generate native ARM binaries on Linux, OS X, and Windows (with Cygwin) platforms.

It provides a set of system headers for stable native APIs that are guaranteed to be supported in all later releases of the platform: