我们来实现下在java代码中调用C代码。
首先第一步:在eclipse中创建HelloWorldFormC的android项目,然后在HelloWorldFormCActivity中定义一个C方法的接口:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class HelloWorldFormCActivity extends Activity {
//1.定义一个C方法的接口,相当于在java代码中定义了一个接口,接口的实现方法是C语言
public native String helloWorldFormC();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
第二步:实现C代码,在项目下新建Folder命名为jni,在jni内新建File文件 例如Hello.c
c代码如下:
#include <stdio.h>
#include <jni.h>
jstring Java_com_xiaomai_HelloWorldFormCActivity_helloWorldFormC(JNIEnv* env,jobject obj){
// 返回一个java String 类型的字符串
//jstring (*NewStringUTF)(JNIEnv*, const char*);
//(*env) 相当于 JNINativeInterface* JNIEnv
//*(*env) 相当于 JNINativeInterface
//return (**env).NewStringUTF(env,"helloworldfromc");
return (*env)->NewStringUTF(env, "helloworldfromc");
}
jni.h是java虚拟机在如下目录中
可以这个文件中找到我们写程序时需要的一些C方法接口;
第三步 生成android.mk文件,android.mk是C代码和java代码关联的脚本语言,作用是告诉编译器如何把C代码打包成函数库给java使用。
打开这个html中有介绍android.mk
我们拷贝使用如下这段代码:
在jni目录下新建android,mk文件,android,mk中代码如下:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
#对应的打包成函数库的名字
LOCAL_MODULE := hello
#对应的c代码的文件
LOCAL_SRC_FILES := hello.c
include $(BUILD_SHARED_LIBRARY)
第四步 把C代码打包成函数库:先cygwin切换到HelloWorldFormC工程目录下然后执行ndk-build
执行完成后刷新项目会看到如下一些文件
hello.o是hello.c的中间文件,android把hello.o文件进行优化成hello.o.d文件,然后这个文件打包后生成的就是armeabi目录下的libhello.so文件(armeabi的意思是 arme cup android binary interface);
第五步 在java代码中引入库函数
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class HelloWorldFormCActivity extends Activity {
//1.定义一个C方法的接口,相当于在java代码中定义了一个接口,接口的实现方法是C语言
public native String helloWorldFormC();
//5.在java代码中引入库函数
static{
System.loadLibrary("hello");//去掉前面的lib和后面的.so。
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void click(View view){
Toast.makeText(getApplicationContext(), helloWorldFormC(), 0).show();
}
}
android的布局文件main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:onClick="click"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
最后运行下程序结果如下: