第一次搞NDK遇到 了很多问题,通过搜索请教终于搞定 下面是一些问题的总结,以便备用.
1.为什么使用NDK,这个要清楚
1.代码的保护。由于apk的java层代码很容易被反编译,而C/C++库反汇难度较大。
2.可以方便地使用现存的开源库。大部分现存的开源库都是用C/C++代码编写的。
3.提高程序的执行效率。将要求高性能的应用逻辑使用C开发,从而提高应用程序的执行效率。
4.便于移植。用C/C++写得库可以方便在其他的嵌入式平台上再次使用。
2.使用方法:这是从developer.com看到的 能力有限就不翻译了,大家自己体会
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. If you use this approach, your application must target specific, minimum Android platform levels, see Android platform compatibility for more information.
-
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.
-
这大概是说framework提供的调用native code的两种方式:传统的在C/C++模块入口中提供native方法注册和NDK提供的方式,就是不用显式的注册,只需要按照java类名在命名native方法。具体的大家可以看这个博客:http://blog.youkuaiyun.com/lymon01/article/details/6643620
3.关于环境配置:
1.这里下载ndk就不再说了NDK地址:http://developer.android.com/sdk/ndk/index.html
2.下载安装cygwin:刚开始很迷惑 ,安装这个干什么 ?搜索了解到cygwin是一个在windows平台上运行的unix模拟环境,它对于学习unix/linux操作环境,或者从unix到windows的应用程序移植,非常有用。通过它,你就可以在不安装linux的情况下使用NDK来编译C、C++代码了。下载地址:http://www.cygwin.com。安装的时候挺郁闷的,选了下载地址后不知道怎么选要安装的包,这让我一阵折腾,听大神说要装这些东西:
autoconf automake binutils gcc-core gcc-g++ gcc4-core gcc4-g++ gdb pcre pcre-devel gawk make 我就这么做了。装完测试命令时发现make命令不好使,只能死马当活马医了,我又运行了安装程序,在选包时只选了make的那个包,结果装完就好了。也就是说选择包时漏了也没关系,重新选就可以了,不必担心啊,呵呵。然后就是一通配置了,cdt、eclipse 编译器等等。
使用javah生成.h文件时又遇到 了问题,总是提示类找不到,那是因为bin目录下还有一层目录 classes。所以就要把命令改为bin/classes了。然后生成.h文件,这个.h文件其实提供的就是一套规范,我们就是根据它编写相应的native code的。然后就是运行了ok大功告成。。。
还有个问题就是把ndk自带的samples导入eclipse,刚开始怎么也导不进去 ,原来是要new 工程选android---android project from Existing Code再选路径就OK了。。。
最后推荐一个不错的博客:http://www.cnblogs.com/devinzhang/archive/2012/02/29/2373729.html