这段时间接触到JNI的东西,网上虽然有很多写的不错的例子,还是写下自己的历程。
我的环境是:XP\android开发环境。
1:下载安装Cygwin.
Cygwin is:
- a collection of tools which provide a Linux look and feel environment for Windows.
- a DLL (cygwin1.dll) which acts as a Linux API layer providing substantial Linux API functionality.
具体安装过程:http://www.programarts.com/cfree_ch/doc/help/UsingCF/CompilerSupport/Cygwin/Cygwin1.htm
鉴于可能出现的问题,在做这一步安装时建议全部安装,虽然有点耗时,我根据楼主的选择来安装是不行的
2:下载NDK
地址:http://developer.android.com/sdk/ndk/index.html
下载解压后放在磁盘任意位置,在配置一下path即可。
3:新建一个android程序,名为:“HelloJniTest”。在这个android程序中新建一个“jni”文件夹,这个文件夹中用于存放Android.mk.和hello-jni.c。
相关代码:
activity:
package cn.com;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloJniTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText( stringFromJNI() );
setContentView(tv);
}
/* A native method that is implemented by the
* 'hello-jni' native library, which is packaged
* with this application.
*/
public native String stringFromJNI();
/* This is another native method declaration that is *not*
* implemented by 'hello-jni'. This is simply to show that
* you can declare as many native methods in your Java code
* as you want, their implementation is searched in the
* currently loaded native libraries only the first time
* you call them.
*
* Trying to call this function will result in a
* java.lang.UnsatisfiedLinkError exception !
*/
public native String unimplementedStringFromJNI();
/* this is used to load the 'hello-jni' library on application
* startup. The library has already been unpacked into
* /data/data/com.example.HelloJni/lib/libhello-jni.so at
* installation time by the package manager.
*/
static {
System.loadLibrary("hello-jni");
}
}
Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := hello-jni.c
include $(BUILD_SHARED_LIBRARY)
hello-jni.c
#include <string.h>
#include <jni.h>
/* This is a trivial JNI example where we use a native method
* to return a new VM String. See the corresponding Java source
* file located at:
*
* apps/samples/hello-jni/project/src/com/example/HelloJni/HelloJni.java
*/
jstring
Java_cn_com_HelloJniTestActivity_stringFromJNI( JNIEnv* env,
jobject thiz )
{
return (*env)->NewStringUTF(env, "Hello from JNI !");
}
在hello-jni.c中,cn_com:是包名
HelloJniTestActivity:是Acivity的名称
stringFromJNI:是activity中的本地方法。
基本的代码准备工作已经完成。
4:用cygwin和NDK来编译生成需要的.so文件。
先在cywin中将路径指定到项目更目录。

然后执行以上命令:d/android-ndk-r8/是前面下载的NDK文件
这时候你会看到你工程内生成需要的libs和obj两个文件夹。
refresh工程项目,最后再将AndroidManifest.xml添加或修改 <uses-sdk android:minSdkVersion="3" /> 即可。