一、什么是JNI
JNI是Java Native Interface的缩写(Java本地调用),Java程序中的函数可以调用Native语言写的函数(一般指的是C/C++编写的函数),Native语言写的函数可以调用Java层的函数。
二、为什么要有JNI
Java语言的跨平台是因为在不同平台上可以运行Java虚拟机,而虚拟机是跑在具体平台上的,而本质上Java是通过JNI技术实现的跨平台,很多基层的模块在Java语言诞生之前已经有了比较优秀的实现,为了避免重复造轮子所以我们要使用JNI技术来使用已有的模块。
三、Mac OS上的环境搭建
在这里说明一下Max OS上的所需环境搭建,Windows和Linux的请搜索相关资料。
1、安装JDK(此处省略)。
2、安装ADT(Android Develop Tools),包括SDK和ADT插件,下载地址:http://pan.baidu.com/s/1o6OBIHG
3、安装Xcode可以去苹果商店下载安装(免费)。
4、安装Apache ANT(下载地址:http://ant.apache.org/bindownload.cgi)详细安装过程可以参考:http://blog.csdn.net/song_hui_xiang/article/details/14315529
5、安装GNU Make(默认已经安装,所以不用安装)可以使用 make -version命令验证是否安装。
6、安装NDK(下载地址:http://pan.baidu.com/s/1i3l5L8T),解压后在用户根目录下新建文件.bash_profile然后添加如下两行(配置环境变量,可以暂时不配置)。
注意:后面的地址是你解压后的目录
关于上面部分开发工具简要介绍:
1、Apache Ant,是一个将软件编译、测试、部署等步骤联系在一起加以自动化的一个工具,大多用于Java环境中的软件开发。
2、NDK是Android原生开发工具包,可以支持C/C++等原生编程语言开发Android应用,它提供头文件、库和交叉编译工具链。
四、第一个示例程序
转载请说明出处:http://blog.csdn.net/dawanganban
1、为eclipse指定NDK路径
2、导入Android NDK中的示例代码(导入hello-jni工程),做过Android开发的朋友应该很熟悉,这里就不啰嗦了。
3、向项目中添加原生支持
项目——>右击——>Android Tools——>Add Native Support
该项目其实已经包含了一个原生项目,所以这一步可以跳过,我们直接Finish继续。
4、插上手机(模拟器太慢了,建议使用真机)运行项目。在C/C++界面视图我们可以看到如下信息
这个过程其实就是在构建原生组件并和Java应用程序打包的过程。此时在我们手机上就可以看到一行文字
五、项目结构及主要目录介绍
1、jni目录:包含原生组件的源代码及描述原生组件构建方法的Make文件(Android.mk),该目录作为NDK构建项目时的构建目录。
2、libs目录:包含指定目标平台的独立子目录,在打包时该目录被包含在apk文件中。
3、obj目录:这是一个中间目录,编译源码后产生的目标文件都保存在该目录下,我们最好不用访问该目录。
六、 实例工程解析
Android.mk的内容如下
有关Makefile的知识请参考我的另一篇博文:http://blog.csdn.net/dawanganban/article/details/38750151
第一行:Android.mk文档必须以LOCAL_PATH变量的定义开头,my-dir是一个系统的宏定义,来定义源文件的目录位置。
第二行:Android构建系统将CLEAR_VARS变量设置为clear-vars.mk片段的位置,更多片段的makefile文件请看ndk\build\core目录,如下:
作用是清除除了LOCAL_PATH以外的LOCAL_<name>变量,这样可以避免冲突。
第三行:每一个原生组件被称为一个模块,LOCAL_MODULE变量用来给这些模块设定一个唯一的名称。
第四行:LOCAL_SRC_FILES变量定义用来建立和组装这个模块的源文件列表,用空格隔开。
第五行:指明了build-shared-library.mk文件的保存位置,该片段包含了将源文件构建成共享库的必要过程。
下面我们来看看HelloJni.java
从上面可以看到调用了原生的stringFromJNI()方法,使用关键字native来通知Java编译器,这个是用另一种语言实现的,再通过加装共享库(static语句块)hello-jni来告诉虚拟机原生方法的具体实现。java.lang.System类提供了两个静态方法,load和loadLibrary用来运行时加载共享库。下面我们来看看具体的实现。
第一个参数JNIEnv是指向可用JNI函数表的接口指针,第二个参数jobject是HelloJni类实例的java对象。最后一句代码是用c字符串创建UTF-8的Java字符串。