用向导新建一个Android工程后, 新建一个MyJni类:
MyJni.java:
package com.jk;
public class MyJni {
static {
System.loadLibrary("myjni");
}
public native int add(int a, int b);
public native int getStr(byte [] str);
}
确认Android工程源码所在目录路径, 如我的工程目录在:/home/jk/workspace/HelloWorld
则,进入/home/jk/workspace/HelloWorld/bin/classes目录,里面存放所有java文件编译出来的class文件
在终端执行命令,生成头文件:
javah com.jk.MyJni
mkdir myjni
cp com_jk_MyJni.h myjni
在myjni目录里,增加文件:
/* com_jk_MyJni.cpp */
#include "com_jk_MyJni.h"
#include <string.h>
JNIEXPORT jint JNICALL Java_com_jk_MyJni_add
(JNIEnv *env, jobject obj, jint a, jint b)
{
return a+b;
}
JNIEXPORT jint JNICALL Java_com_jk_MyJni_getStr
(JNIEnv *env, jobject obj, jbyteArray arr)
{
unsigned char *data = (unsigned char *)env->GetByteArrayElements(arr, 0);
int len = env->GetArrayLength(arr);
strcpy((char *)data, "hello");
int ret = strlen((char *)data);
env->SetByteArrayRegion(arr, 0, len, (jbyte *)data);
return ret;
}
/* Android.mk */
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := myjni
LOCAL_MODULE_TAGS := optional
LOCAL_SRC_FILES := com_jk_MyJni.cpp
include $(BUILD_SHARED_LIBRARY)
/* App.mk */
APP_BUILD_SCRIPT := Android.mk
完成上面操作后,在android系统源码目录下:
. ./build/envsetup.sh
lunch dolphin_fvd_p1-eng
环境变量生成后, 再进入myjni目录:
ndk-build NDK_PROJECT_PATH=. NDK_APPLICATION_MK=App.mk
完成后,把生成的libs目录里的内容复制到android工程目录里的libs目录里:
cp libs/* ~/workspace/HelloWorld/libs/ -rf
完成,再修改MainActivity.java, 调用动态库:
package com.example.helloworld;
import com.jk.MyJni;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button btn1, btn2;
private TextView txt;
private MyJni myjni = new MyJni();
private OnClickListener lt = new OnClickListener() {
public void onClick(View arg0) {
System.out.printf("ret = %d\n", myjni.add(88, 99));
int l = myjni.getStr(data);
System.out.printf("l = %d\n", l);
System.out.println(new String(data, 0, l));
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.button1);
btn2 = (Button)findViewById(R.id.button3);
btn1.setOnClickListener(lt);
btn2.setOnClickListener(lt);
}
...
}
点击按钮后就可以在 logcat里看到程序的输出