eclipse下兩種配置方式:
一種是右鍵工程選擇properties->builders->new->program,然後再做相應的選擇,因爲這種方式我沒有嘗試過,網上也有例子,所以我就不做詳細的說明。
另一種方式:先加載ndk路徑:
選擇標題欄的Eclipse->Preferences->
然後選擇NDK的路徑即可。
接下來新建一個android工程:TestJNI
然後右鍵工程
然後左鍵點一下你的工程就發現
這個小錘子就可以使用了,這個工具就是用來生成so文件的
接下來就是java調用c/c++的過程了(睜大眼睛,不要走開)
在這裏我們新建一個JNIClient.java類用來調用本地相關文件
-
package com.example.wade;
-
-
-
-
publicclass JNIClient {
-
-
-
static publicnative String AddStr(String strA,String strB);
-
-
-
static publicnative int AddInt(int a,int b);
-
-
}
然後我們使用mac的控制檯terminal,cd到JNIClient.java的目錄,然後javac JNIClient.java生成JNIClient.class文件
然後我們再cd到src目錄javah com.example.wade.JNIClient,會在src目錄下生成com.example.wade.JNIClient.h文件
把這個h文件放在jni目錄下,同時新建一個c文件,mk文件裏
-
LOCAL_SRC_FILES := com_example_wade_JNIClient.c
最後重寫C文件
-
#include"com_example_wade_JNIClient.h"
-
-
#include<stdlib.h>
-
-
#include<stdio.h>
-
-
-
-
#ifdef __cplusplus
-
-
extern"C" {
-
-
#endif
-
-
-
-
-
-
-
-
-
-
-
-
JNIEXPORT jstring JNICALL Java_com_example_wade_JNIClient_AddStr(JNIEnv *env,
-
-
jclass arg, jstring a, jstring b) {
-
-
jstring str = (*env)->NewStringUTF(env,"HelloWorld from JNI !");
-
-
return str;
-
-
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
JNIEXPORT jint JNICALL Java_com_example_wade_JNIClient_AddInt(JNIEnv *env, jclass arg,
-
-
jint a, jint b) {
-
-
return a + b;
-
-
}
-
-
-
-
#ifdef __cplusplus
-
-
}
-
-
#endif
終於到了激動人心的一步了(最後最後一步了)
-
public class MainActivityextends Activity {
-
-
-
static{
-
-
System.loadLibrary("wade");
-
-
}
-
-
-
-
@Override
-
-
protected void onCreate(Bundle savedInstanceState) {
-
-
super.onCreate(savedInstanceState);
-
-
setContentView(R.layout.activity_main);
-
-
-
String str = JNIClient.AddStr("","");
-
-
System.out.println(""+str);
-
-
int sum = JNIClient.AddInt(3, 4);
-
-
System.out.println("sum:"+sum);
-
-
}
-
-
-
-
@Override
-
-
public boolean onCreateOptionsMenu(Menu menu) {
-
-
-
-
getMenuInflater().inflate(R.menu.main, menu);
-
-
returntrue;
-
-
}
-
-
-
-
}
在我們的主類裏調用庫文件,然後進行相應方法的調用即可。
這時候運行程序,會發現已經成功!!!