1. 下载NDK, 本次版本为 r9d
wget
tar jxvf android-ndk-r9d-linux-x86.tar.bz2
cd android-ndk-r9d
mkdir jni
#将下面2个文件(qiushui_jni.c, Android.mk) 用Winscp拷贝到jni目录下即可. 编译命令如下
./ndk-build
#编译时会看到最后一行为如下:
[armeabi] Install : libqiushui_jni.so => libs/armeabi/libqiushui_jni.so
#然后在./libs/armeabi下就能看到刚刚生成的.so文件, 将此文件用WINSCP拷贝到安卓工程的同样目录下即可.
2. NDK下的C编程和android.mk
-
//文件名: qiushui_jni.c
-
-
#include <jni.h>
-
#include <android/log.h>
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
-
#define DBG (1) //1=Log cat输出, 0=false
-
#define JNI_LOG "qiushui"
-
-
//-------------------------------------------------------------------------------------------------
-
//接收java中的数组, 运算后返回int类型
-
JNIEXPORT jint JNICALL Java_qiushui_Jni_getInt(JNIEnv *env, jobject obj, jintArray arr, jint len)
-
{
-
jint buf[len];
-
jint i, sum = 0;
-
-
(*env)->GetIntArrayRegion(env, arr, 0, len, buf);
-
for (i = 0; i < len; i++) {
-
sum += buf[i];
-
}
-
-
return sum;
-
}
-
-
//接收java中的String, 修改后返回String
-
JNIEXPORT jstring JNICALL Java_qiushui_Jni_getString(JNIEnv *env, jobject obj, jstring str)
-
{
-
char outbuf[128];
-
int len = (*env)->GetStringLength(env, str);
-
-
(*env)->GetStringUTFRegion(env, str, 0, len, outbuf);
-
if (DBG) __android_log_print(ANDROID_LOG_INFO, JNI_LOG, "Java->JNI: %s", outbuf);
-
strcat(outbuf, "---qiushui_007");
-
-
return (*env)->NewStringUTF(env, outbuf);
-
}
-
#文件名: Android.mk
-
LOCAL_PATH := $(call my-dir)
-
-
include $(CLEAR_VARS)
-
-
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
-
LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -llog
-
-
LOCAL_MODULE := qiushui_jni
-
LOCAL_SRC_FILES := qiushui_Jni.c
-
-
include $(BUILD_SHARED_LIBRARY)
3. android下java编程
3.1 首先写个调用so的类
-
package qiushui;
-
-
public class Jni {
-
static {
-
System.loadLibrary("qiushui_jni");
-
}
-
-
public native int getInt(int[] arr, int len);
-
public native String getString(String str);
-
}
3.2 然后主进程中就可以自由调用了
-
package huang.feng;
-
-
import qiushui.Jni;
-
-
import android.app.Activity;
-
import android.os.Bundle;
-
import android.widget.TextView;
-
-
public class HelloNDKActivity extends Activity {
-
/** Called when the activity is first created. */
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
// setContentView(R.layout.main);
-
TextView textView = new TextView(this);
-
-
Jni jni = new Jni();
-
String str_test = "JNI str test: ";
-
int[] arr_int = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
-
int len = arr_int.length;
-
textView.setText(jni.getString(str_test) + ", int = " + jni.getInt(arr_int, len));
-
-
setContentView(textView);
-
}
-
}
阅读(1865) | 评论(0) | 转发(0) |