TheAndroidNDKisatoolsetthatletsyouembedcomponentsthatmakeuseofnativecodeinyourAndroidapplications.
AndroidNDK是一个工具集,它让我们能够在Android应用程序中使用由本地代码(nativecode)编写的代码模块。
AndroidapplicationsrunintheDalvikvirtualmachine.TheNDKallowsyoutoimplementpartsofyourapplicationsusingnative-codelanguagessuchasCandC++.Thiscanprovidebenefitstocertainclassesofapplications,intheformofreuseofexistingcodeandinsomecasesincreasedspeed.
Android应用程序在Dalvik虚拟机中运行,NDK让我们可以将应用程序中的某些部分用本地代码(nativecode)语言(例如C和C++)来实现,这样会对部分应用程序有益处,例如可以代码重用,提高运行速度等。
TheNDKprovides:
NDK工具集提供的内容包括:
·AsetoftoolsandbuildfilesusedtogeneratenativecodelibrariesfromCandC++sources
用于将C和C++源代码生成本地代码库(nativecodelibraries)的一套工具和编译文件(buildfiles)
·Awaytoembedthecorrespondingnativelibrariesintoanapplicationpackagefile(.apk)thatcanbedeployedonAndroiddevices
将相应的本地库(nativelibraries)嵌入进应用程序包文件(apk)的方法
·AsetofnativesystemheadersandlibrariesthatwillbesupportedinallfutureversionsoftheAndroidplatform,startingfromAndroid1.5.ApplicationsthatusenativeactivitiesmustberunonAndroid2.3orlater.
一套本地系统头文件和库,这些头文件和库从Android1.5版本开始,及其后续所有版本的Android平台中都会支持。使用nativeactivities的应用程序则必须运行在Android2.3及其以后的版本上。
·Documentation,samples,andtutorials
各类文档,实例程序及各类指导材料。
ThelatestreleaseoftheNDKsupportsthefollowinginstructionsets:
最新release的NDK支持如下的指令集:
·ARMv5TE,includingThumb-1instructions(seedocs/CPU-ARCH-ABIS.htmlformoreinformation)
·ARMv7-A,includingThumb-2andVFPv3-D16instructions,withoptionalsupportforNEON/VFPv3-D32instructions(seedocs/CPU-ARM-NEON.htmlformoreinformation)
·x86instructions(seedocs/CPU-X86.htmlformoreinformation)
·MIPSinstructions(seedocs/CPU-MIPS.htmlformoreinformation)
ARMv5TEmachinecodewillrunonallARM-basedAndroiddevices.ARMv7-AwillrunonlyondevicessuchastheVerizonDroidorGoogleNexusOnethathaveacompatibleCPU.ThemaindifferencebetweenthetwoinstructionsetsisthatARMv7-AsupportshardwareFPU,Thumb-2,andNEONinstructions.Youcantargeteitherorbothoftheinstructionsets—ARMv5TEisthedefault,butswitchingtoARMv7-Aisaseasyasaddingasinglelinetotheapplication'sApplication.mkfile,withoutneedingtochangeanythingelseinthefile.Youcanalsobuildforbotharchitecturesatthesametimeandhaveeverythingstoredinthefinal.apk.CompleteinformationisprovidedintheCPU-ARCH-ABIS.HTMLintheNDKpackage.
ARMv5TE机器码可以在所有基于ARM的Android设备上运行。ARMv7-A机器码只可以在VerizonDroid或者GoogleNexusOne等这类拥有兼容CPU(compatibleCPU)的设备上运行。这两种指令集之间的主要差别是ARMv7-A支持硬件FPU,Thumb-2和NEON指令。ARMv5TE是默认的指令集,要切换到ARMv7-A也很容易,只需要在应用程序的Application.mk文件中添加一行语句,文件中的其它内容则都不需要修改。我们也可以同时使用这两种指令集,并且都存放进最终的apk文件中。完整的信息请参考NDK包中的CPU-ARCH-ABIS.HTML文件。
NDK为libc,libm,OpenGLES,JNI接口和其它的一些库提供了稳定的头文件。(全部的库请参考DevelopmentTools章节)
WhentoDevelopinNativeCode
何时需要使用本地代码开发
TheNDKwillnotbenefitmostapplications.Asadeveloper,youneedtobalanceitsbenefitsagainstitsdrawbacks;notably,usingnativecodedoesnotresultinanautomaticperformanceincrease,butalwaysincreasesapplicationcomplexity.Ingeneral,youshouldonlyusenativecodeifitisessentialtoyourapplication,notjustbecauseyouprefertoprograminC/C++.
大部分的应用程序都不会从NDK收益。作为一个开发者,我们需要平衡它能带给我们的好处和它所带来的问题,尤其是,使用本地代码不一定会带来性能上的提升,但是一定会增加程序的复杂度。通常情况下,只有在对应用程序十分必要的情况才应该使用本地代码,而不是仅仅因为喜欢用C或者C++编程。
TypicalgoodcandidatesfortheNDKareself-contained,CPU-intensiveoperationsthatdon'tallocatemuchmemory,suchassignalprocessing,physicssimulation,andsoon.Simplyre-codingamethodtoruninCusuallydoesnotresultinalargeperformanceincrease.Whenexaminingwhetherornotyoushoulddevelopinnativecode,thinkaboutyourrequirementsandseeiftheAndroidframeworkAPIsprovidethefunctionalitythatyouneed.TheNDKcan,however,canbeaneffectivewaytoreusealargecorpusofexistingC/C++code.
典型的需要使用NDK的是那些self-contained,CPU-intensive的操作,不需要申请大量的内存,例如信号处理,物理模拟(physicssimulation)等。简单的使用C语言重新编码一个函数通常不会带来性能上的提升。在分析是否应该使用本地代码进行开发时,需要考虑我们的要求以及是否AndroidframeworkAPIs已经提供了我们需要的功能。然而,要复用大量C/C++代码,NDK是一种高效的方式。
TheAndroidframeworkprovidestwowaystousenativecode:
Androidframework提供了两种方式使用本地代码:
使用Androidframework编写应用程序,然后使用JNI访问AndroidNDK提供的API。这种方式可以利用Androidframework的方便,而且需要的时候依然可以编写本地代码。
编写nativeactivity,这样可以在本地代码中实现生命周期回调函数。AndroidSDK提供了NativeActivity类。
YoucannotaccessfeaturessuchasServicesandContentProvidersnatively,soifyouwanttousethemoranyotherframeworkAPI,youcanstillwriteJNIcodetodoso.
不能够在本地代码中使用Service和ContentProvider等特性,如果要使用这些特性或者其它任何framework的API,可以编写JNI完成。
ContentsoftheNDK
NDK中包含的内容:开发工具,文档,实例程序
TheNDKcontainstheAPIs,documentation,andsampleapplicationsthathelpyouwriteyournativecode.
Developmenttools
TheNDKincludesasetofcross-toolchains(compilers,linkers,etc..)thatcangeneratenativeARMbinariesonLinux,OSX,andWindows(withCygwin)platforms.
NDK包含一套交叉工具链,能够生成运行在Linux,OSX和Windows平台上的本地ARM二进制文件(nativeARMbinaries)。
ItprovidesasetofsystemheadersforstablenativeAPIsthatareguaranteedtobesupportedinalllaterreleasesoftheplatform:
一套系统头文件,头文件中包含稳定的本地APIs,这些本地APIs在以后的release中都会支持:
·libc(Clibrary)headers
·libm(mathlibrary)headers
·JNIinterfaceheaders
·libz(Zlibcompression)headers
·liblog(Androidlogging)header
·OpenGLES1.1andOpenGLES2.0(3Dgraphicslibraries)headers
·libjnigraphics(Pixelbufferaccess)header(forAndroid2.2andabove).
·AMinimalsetofheadersforC++support
·OpenSLESnativeaudiolibraries
·AndroidnativeapplicationAPIS
TheNDKalsoprovidesabuildsystemthatletsyouworkefficientlywithyoursources,withouthavingtohandlethetoolchain/platform/CPU/ABIdetails.YoucreateveryshortbuildfilestodescribewhichsourcestocompileandwhichAndroidapplicationwillusethem—thebuildsystemcompilesthesourcesandplacesthesharedlibrariesdirectlyinyourapplicationproject.
NDK提供的编译系统让我们可以高效的编译源码,不需要去处理工具链、平台等细节。我们只需要创建很短的编译文件,描述哪些源文件要编译以及哪些应用程序会使用它们,编译系统就会编译源代码并且将编译生成的共享库(sharedlibraries)直接放到我们的应用程序中。
Important:Withtheexceptionofthelibrarieslistedabove,nativesystemlibrariesintheAndroidplatformarenotstableandmaychangeinfutureplatformversions.YourapplicationsshouldonlymakeuseofthestablenativesystemlibrariesprovidedinthisNDK.
除去上面所列的库外,其它的本地系统库是不稳定的,在以后的版本中可能会改变,因此我们的应用程序应该避免使用不稳定的库,而只使用NDK中提供的稳定的本地系统库。
Documentation
TheNDKpackageincludesasetofdocumentationthatdescribesthecapabilitiesoftheNDKandhowtouseittocreatesharedlibrariesforyourAndroidapplications.Inthisrelease,thedocumentationisprovidedonlyinthedownloadableNDKpackage.Youcanfindthedocumentationinthe
NDK包包含了一套文档,这些文档描述了NDK的功能,以及如何使用它为Android应用程序创建共享库(sharedlibraries)。在这次release中,这些文档只在下载的NDK包中提供,可以在docs目录下查看,包括如下的文件:
·INSTALL.HTML—describeshowtoinstalltheNDKandconfigureitforyourhostsystem
·OVERVIEW.HTML—providesanoverviewoftheNDKcapabilitiesandusage
·ANDROID-MK.HTML—describestheuseoftheAndroid.mkfile,whichdefinesthenativesourcesyouwanttocompile
描述Android.mk文件的使用,Android.mk文件定义要编译的本地源文件
·APPLICATION-MK.HTML—describestheuseoftheApplication.mkfile,whichdescribesthenativesourcesrequiredbyyourAndroidapplication
·CPLUSPLUS-SUPPORT.HTML—describestheC++supportprovidedintheAndroidNDK
描述AndroidNDK对C++的支持
·CPU-ARCH-ABIS.HTML—adescriptionofsupportedCPUarchitecturesandhowtotargetthem.
描述了支持的CPU架构
·CPU-FEATURES.HTML—adescriptionofthecpufeaturesstaticlibrarythatletsyourapplicationcodedetectthetargetdevice'sCPUfamilyandtheoptionalfeaturesatruntime.
描述了cpufeature静态库,它可以让我们的应用程序代码在运行时探测目标设备的CPUfamily和其它的特性
·CHANGES.HTML—acompletelistofchangestotheNDKacrossallreleases.
·DEVELOPMENT.HTML—describeshowtomodifytheNDKandgeneratereleasepackagesforit
·HOWTO.HTML—informationaboutcommontasksassociatedwithNDKdevelopment
·IMPORT-MODULE.HTML—describeshowtoshareandreusemodules
·LICENSES.HTML—informationaboutthevariousopensourcelicensesthatgoverntheAndroidNDK
·NATIVE-ACTIVITY.HTML—describeshowtoimplementnativeactivities
描述如何实现nativeactivities
·NDK-BUILD.HTML—describestheusageofthendk-buildscript
·NDK-GDB.HTML—describeshowtousethenativecodedebugger
·PREBUILTS.HTML—informationabouthowsharedandstaticprebuiltlibrarieswork
共享库和静态库如何工作方面的信息
·STANDALONE-TOOLCHAIN.HTML—describeshowtouseAndroidNDKtoolchainasastandalonecompiler(stillinbeta).
·SYSTEM-ISSUES.HTML—knownissuesintheAndroidsystemimagesthatyoushouldbeawareof,ifyouaredevelopingusingtheNDK.
·STABLE-APIS.HTML—acompletelistofthestableAPIsexposedbyheadersintheNDK.
NDK中的头文件导出的稳定API的完整列表
Additionally,thepackageincludesdetailedinformationaboutthe"bionic"ClibraryprovidedwiththeAndroidplatformthatyoushouldbeawareof,ifyouaredevelopingusingtheNDK.Youcanfindthedocumentationinthe
·OVERVIEW.HTML—providesanoverviewofthe"bionic"Clibraryandthefeaturesitoffers.
提供了“bionic”的概述,以及它所提供的特性
Sampleapplications
TheNDKincludessampleapplicationsthatillustratehowtousenativecodeinyourAndroidapplications:
·hello-jni—asimpleapplicationthatloadsastringfromanativemethodimplementedinasharedlibraryandthendisplaysitintheapplicationUI.
·two-libs—asimpleapplicationthatloadsasharedlibrarydynamicallyandcallsanativemethodprovidedbythelibrary.Inthiscase,themethodisimplementedinastaticlibraryimportedbythesharedlibrary.
·hello-gl2—asimpleapplicationthatrendersatriangleusingOpenGLES2.0vertexandfragmentshaders.
·hello-neon—asimpleapplicationthatshowshowtousethecpufeatureslibrarytocheckCPUcapabilitiesatruntime,thenuseNEONintrinsicsifsupportedbytheCPU.Specifically,theapplicationimplementstwoversionsofatinybenchmarkforaFIRfilterloop,aCversionandaNEON-optimizedversionfordevicesthatsupportit.
·native-activity—asimpleapplicationthatdemonstrateshowtousethenative-app-gluestaticlibrarytocreateanativeactivity
·native-plasma—aversionofbitmap-plasmaimplementedwithanativeactivity.
Foreachsample,theNDKincludesthecorrespondingCsourcecodeandthenecessaryAndroid.mkandApplication.mkfiles.Therearelocatedunder
Youcanbuildthesharedlibrariesforthesampleappsbygoinginto
Next,buildthesampleAndroidapplicationsthatusethesharedlibraries:
·IfyouaredevelopinginEclipsewithADT,usetheNewProjectWizardtocreateanewAndroidprojectforeachsample,usingthe"ImportfromExistingSource"optionandimportingthesourcefrom
·IfyouaredevelopingwithAnt,usetheandroidtooltocreatethebuildfileforeachofthesampleprojectsat
Exploringthenative-activitySampleApplication
Thenative-activitysampleprovidedwiththeAndroidNDKdemonstrateshowtousetheandroid_native_app_gluestaticlibrary.Thisstaticlibrarymakescreatinganativeactivityeasierbyprovidingyouwithanimplementationthathandlesyourcallbacksinanotherthread,soyoudonothavetoworryaboutthemblockingyourmainUIthread.Themainpartsofthesamplearedescribedbelow:
native-activity实例展示了如何使用android_native_app_glue静态库
·Ajni/directorycontainsthenativeactivity,main.c,whichusestheandroid_native_app_glue.hinterfacetoimplementtheactivity.The