`
sony-soft
  • 浏览: 1021511 次
文章分类
社区版块
存档分类
最新评论

Android NDK Overview

 
阅读更多
原文:NDK的文档OVERVIEW.html
这篇文章粗略介绍了应用中使用native,构建NDK,调试应以及相关需要参考哪些文档

Introduction:
The Android NDK is a set of tools that allows Android application developersto embed native machine code compiled from C and/or C++ source files intotheir application packages.

IMPORTANT:
The Android NDK can only be used to target Android system imagesrunning Cupcake (a.k.a 1.5) or later versions of the platform. 1.0 and 1.1 system images are specifically *not* supported due tosubtle ABI and toolchain changes that happened for the 1.5 release.
只适用于1.5以上

Android NDK Goals:
The Android VM allows your application's source code to call methodsimplemented in native code through the JNI. In a nutshell, this means that:Your application's source code will declare one or more methodswith the 'native' keyword to indicate that they are implemented throughnative code. E.g
native byte[]  loadFile(String  filePath);
在代码里使用关键字native表示某些方法由native来实现

You must provide a native shared library that contains theimplementation of these methods, which will be packaged into yourapplication's .apk. This library must be named according to standardUnix conventions as lib<something>.so, and shall contain a standard JNIentry point (more on this later). For example:libFileLoader.so
必须提供实现这些方法的native shared library,它们将被package到app的apk中。这些library的命名必须遵循标准Unix风格,比如lib***.so,而且还要包含一个标准的JNI entry point。

Your application must explicitly load the library. For example, to load it at application start-up, simply add the following to its source code:
static {
        System.loadLibrary("FileLoader");
      }
在App中必须显式加载library,比如使用以上代码在App启动时加载library

Note that you should not use the 'lib' prefix and '.so' suffix here.
注意,此处不要使用lib前缀和so后缀

The Android NDK is a complement to the Android SDK that helps you to:
NDK是SDK的一个补充
- Generate JNI-compatible shared libraries that can run on the Android1.5 platform (and later) running on ARM CPUs.
- Copy the generated shared libraries to a proper location of yourapplication project path, so they will be automatically added to yourfinal (and signed) .apks
把生成的shared libraries拷贝到应用工程的正确的路径,将被自动加入最后的apk
- In later revisions of the NDK, we intend to provide tools that helpdebug your native code through a remote gdb connection and as muchsource/symbol information as possible.

Moreover, the Android NDK provides:
- A set of cross-toolchains (compilers, linkers, etc..) that cangenerate native ARM binaries on Linux, OS X and Windows (with Cygwin)
- A set of system headers corresponding to the list of stable native APIssupported by the Android platform. This corresponds to definitions thatare guaranteed to be supported in all later releases of the platform.

They are documented in the file docs/STABLE-APIS.html

IMPORTANT:
Keep in mind that most of the native system libraries in Android systemimages are not frozen and might changed drastically, or even deleted, in later updates and releases of the platform.
- A build system that allow developers to only write very short build filesto describe which sources need to be compiled, and how. The build systemdeals with all the hairy toolchain/platform/CPU/ABI specifics. Moreover,later updates of the NDK can add support for more toolchains, platforms,system interfaces without requiring changes in the developer's buildfiles (more on this later).



II. Android NDK Non-Goals:
--------------------------
The NDK is *not* a good way to write generic native code that runs on Androiddevices. In particular, your applications should still be written in the Javaprogramming language, handle Android system events appropriately to avoid the"Application Not Responding" dialog or deal with the Android applicationlife-cycle.
NDK并不是一种在Android设备上运行native code的好途径

Note however that is is possible to write a sophisticated application innative code with a small "application wrapper" used to start/stop itappropriately.

A good understanding of JNI is highly recommended, since many operationsin this environment require specific actions from the developers, that arenot necessarily common in typical native code. These include:
- Not being able to directly access the content of VM objects throughdirect native pointers. E.g. you cannot safely get a pointer to aString object's 16-bit char array to iterate over it in a loop.
- Requiring explicit reference management when the native code wants tokeep handles to VM objects between JNI calls.

The NDK only provides system headers for a very limited set of native APIs and libraries supported by the Android platform. While a typicalAndroid system image includes many native shared libraries, these shouldbe considered an implementation detail that might change drastically betweenupdates and releases of the platform.

If an Android system library is not explicitly supported by the NDKheaders, then applications should not depend on it being available, orthey risk breaking after the next over-the-air system update on various
devices.

Selected system libraries will gradually be added to the set of stable NDKAPIs.

III. NDK development in practice:
---------------------------------
Here's a very rough overview of how you can develop native code with theAndroid NDK:
以下是粗略的介绍

1.Place your native sources under $PROJECT/jni/...
把native源代码放在$PROJECT/jni/...
2. Write $PROJECT/jni/Android.mk to describe your sourcesto the NDK build system
撰写$PROJECT/jni/Android.mk,向NDK系统描述你的源代码
3. Optional: write $PROJECT/jni/Application.mk to describe yourproject in more details to the build system. You don't needone to get started though, but this allows you to targetmore than one CPU or override compiler/linker flags(see docs/APPLICATION-MK.html for all details).
可选操作:撰写$PROJECT/jni/Application.mk,向build system更多地描述你的工程。
4. Build your native code by running "$NDK/ndk-build" from yourproject directory, or any of its sub-directories.
运行"$NDK/ndk-build"来编译

The last step will copy, in case of success, the stripped shared librariesyour application needs to your application's root project directory. Youwill then need to generate your final .apk through the usual means.

Now, for a few more details:

III.1/ Configuring the NDK:
- - - - - - - - - - - - - -
Previous releases required that you run the 'build/host-setup.sh'script to configure your NDK. This step has been removed completelyin release 4 (a.k.a. NDK r4).
NDKr4里已经不需要单独配置NDK

III.2/ Placing C and C++ sources:
- - - - - - - - - - - - - - - - -
Place your native sources under the following directory:
$PROJECT/jni/
Where $PROJECT corresponds to the path of your Android applicationproject.
把native sources放入$PROJECT/jni/

You are pretty free to organize the content of 'jni' as you want,the directory names and structure here will not influence the finalgenerated application packages, so you don't have to use pseudo-unique
names like com.<mycompany>.<myproject> as is the case for applicationpackage names.

Note that C and C++ sources are supported. The default C++ file extensionssupported by the NDK is '.cpp', but other extensions can be handled as well(see docs/ANDROID-MK.html for details).

It is possible to store your sources in a different location by adjustingyour Android.mk file (see below).

III.3/ Writing an Android.mk build script:
- - - - - - - - - - - - - - - - - - - - - -
An Android.mk file is a small build script that you write to describe yoursources to the NDK build system. Its syntax is described in details inthe file docs/ANDROID-MK.html.
Android.mk是一个小的build脚本。用于向NDK build系统描述源码。在docs/ANDROID-MK.html 中有详细的描述。

In a nutshell, the NDK groups your sources into "modules", where each modulecan be one of the following:
- a static library
- a shared library

You can define several modules in a single Android.mk, or you can writeseveral Android.mk files, each one defining a single module.
可以在一个mk文件中定义多个modules,也可以每个mk定义一个module

Note that a single Android.mk might be parsed several times by the buildsystem so don't assume that certain variables are not defined in them.By default, the NDK will look for the following build script:
$PROJECT/jni/Android.mk

If you want to define Android.mk files in sub-directories, you shouldinclude them explicitly in your top-level Android.mk. There is evena helper function to do that, i.e. use:
如果想在子文件夹中定义Android.mk
include $(call all-subdir-makefiles)

This will include all Android.mk files in sub-directories of the currentbuild file's path.

III.4/ Writing an Application.mk build file (optional):
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
While an Android.mk file describes your modules to the build system, theApplication.mk file describes your application itself. See thedocs/APPLICATION-MK.html document to understand what this file allows youto do. This includes, among others:
Android.mk描述了你的modules,Application.mk描述了App。在docs/APPLICATION-MK.html有详细描述。
- The exact list of modules required by your application.
- The CPU architecture(s) to generate machine code for.
- Optional information, like whether you want a release or debug
build, specific C or C++ compiler flags and others that should
apply to all modules being built.
This file is optional: by default the NDK will provide one that simplybuilds *all* the modules listed from your Android.mk (and all the makefilesit includes) and target the default CPU ABI (armeabi).

There are two ways to use an Application.mk:
- Place it under $PROJECT/jni/Application.mk, and it will be pickedup automatically by the 'ndk-build' script (more on this later)
- Place it under $NDK/apps/<name>/Application.mk, where $NDK points to your NDK installation path. After that, launch "make APP=<name>" from the NDK directory.

This was the way this file was used before Android NDK r4.It is still supported for compatibility reasons, but we stronglyencourage you to use the first method instead, since it is much simpler and doesn't need modifying / changing directories of theNDK installation tree.

Again, see docs/APPLICATION-MK.html for a complete description of itscontent.

III.5/ Invoke the NDK build system:
- - - - - - - - - - - - - - - - - -
The preferred way to build machine code with the NDK is to use the'ndk-build' script introduced with Android NDK r4. You can also usea second, legacy, method that depends on creating a '$NDK/apps' subdirectory.
有两种build方式

In both cases, a successful build will copy the final stripped binary modules(i.e. shared libraries) required by your application to your application'sproject path (Note that unstripped versions are kept for debuggingpurposes, there is no need to copy unstripped binaries to a device).

1: Using the 'ndk-build' command:
使用命令‘ndk-build’
---------------------------------
The 'ndk-build' script, located at the top of the NDK installation pathcan be invoked directly from your application project directory (i.e. theone where your AndroidManifest.xml is located) or any of its sub-directories.
脚本‘ndk-build’位于ndk安装目录下
For example:
cd $PROJECT
$NDK/ndk-build
This will launch the NDK build scripts, which will automatically probe yourdevelopment system and application project file to determine what to build.
For example:
ndk-build
ndk-build clean --> clean generated binaries
ndk-build -B V=1 --> force complete rebuild, showing commands
By default, it expects an optional file under $PROJECT/jni/Application.mk,and a required $PROJECT/jni/Android.mk.

On success, this will copy the generated binary modules (i.e. sharedlibraries) to the appropriate location in your project tree. You can laterrebuild the full Android application package either through the usual 'ant' command, or the ADT Eclipse plug-in.
一旦编译完成,将会拷贝生成的binary modules到你工程的正确位置。稍后可以通过ant命令或者ADT来重新构建完整的Android application package。

See docs/NDK-BUILD.html for a more complete description of what this script does and which options it can take.

2: Using the $NDK/apps/<name>/Application.mk:
使用$NDK/apps/<name>/Application.mk
---------------------------------------------
This build method was the only one before Android NDK r4 and is onlysupported for compatibility reason. We strongly recommend you to migrate to using the 'ndk-build' command as soon as possible, since we may remove legacy support in a later NDK release.
这种build方法将被弃用

It requires the following:
1. Creating a sub-directory named $NDK/apps/<name>/ underyour NDK installation directory (not your project path).Where <name> is an arbitrary name to describe your application
to the NDK build system (no spaces allowed).
2. Write $NDK/apps/<name>/Application.mk, which then requiresa definition for APP_PROJECT_PATH that points to yourapplication project directory.
3. Go to the NDK installation path on the command line theninvoke the top-level GNUMakefile, as in:
cd $NDK
make APP=<name>
The result will be equivalent to the first method, except for the factthat intermediate generated files will be placed under $NDK/out/apps/<name>/

IV. Rebuild your application package:
- - - - - - - - - - - - - - - - - - -
After generating the binaries with the NDK, you need to rebuild yourAndroid application package files (.apk) using the normal means, i.e.either using the 'ant' command or the ADT Eclipse plug-in.
用NDK生成了binaries之后,你需要rebuild Android application package files

See the Android SDK documentation for more details. The new .apk willembed your shared libraries, and they will be extracted automaticallyat installation time by the system when you install the package on atarget device.
新的apk将嵌入你的shared libraies,当你在target device上安装package时,它们将被系统自动解压。

V. Debugging support:
- - - - - - - - - - -
The NDK provides a helper script, named 'ndk-gdb' to very easily launcha native debugging session of your applications.

Native debugging can *ONLY* be performed on production devices runningAndroid 2.2 or higher, and does not require root or privileged access, aslong as your application is debuggable.

For more information, read docs/NDK-GDB.html. In a nutshell, native debuggingfollows this simple scheme:
概要
1. Ensure your application is debuggable (e.g. set android:debuggableto "true" in your AndroidManifest.xml)
确认程序可调试
2. Build your application with 'ndk-build', then install it on yourdevice/emulator.
使用ndk-build来构建,并安装在模拟器上
3. Launch your application.
启动应用
4. Run 'ndk-gdb' from your application project directory.
从应用目录启动gdb

You will get a gdb prompt. See the GDB User Manual for a list of usefulcommands.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics