JNI编程(HelloThundersoft)
使用eclipse创建调用JNI程序主要分为以下几个步骤:
1)配置ndk路径。
2)创建工程并增加native支持
3)声明native方法
4)使用javah
-jni生成头文件(com_Thundersoft_hellothundersoft_MainActivity.h)
5)native方法的实现
6)编译生成native库,运行该工程项目
1、配置ndk路径
打开Eclipse后,点击菜单栏的Project->Preferences打开Preferences窗口,点击左侧Android->NDK选项,在右侧NDK
Location填入ndk的路径。
2、创建工程并增加native支持
点击菜单栏的File->New->Android
Application Project创建Android工程(HelloThundersoft)。
创建完毕后,在PackageExplorer中右键点击刚才新建的Android项目,选择Android
Tools->Add Native
Support,按下图填写,点击确认后,工程目录下会增加jni目录,jni目录下有HelloThundersoft.cpp和Android.mk。
3、声明native方法
在MainActivity.java里编写下面的代码:
package com.Thundersoft.hellothundersoft;
importandroid.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
static{
System.loadLibrary("HelloThundersoft");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v) {
Toast.makeText(this,hello(), Toast.LENGTH_SHORT).show();
}
public native String hello();
}
并在布局文件里添加按钮:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="从native获取信息"
android:onClick="click"/>
以上代码列出两个比较重要的要点:一个是加载JNI库;另一个是声明Java的native方法。
静态初始化块里System.loadLibrary中的参数是库的名字,库的名字是指库文件中除去前缀(linnux)和后缀的部分,如LINUX的libHelloThundersoft
.so文件,其库名都是HelloThundersoft。
声明native方法时,必须包含修饰字:native,同时在java编程语言中不应该实现该方法。在native方法被调用前,native库
必须被导入。我们在静态初始化中导入native库。java
VM将在调用MainActivity
类中的任何方法前,先自动地运行静态初始化,这样就保证了在native方法print()在native库被导入之后
才被调用。
4、使用javah -jni生成头文件(com_Thundersoft_hellothundersoft_MainActivity.h)
在工程src目录下执行以下命令可以自动生成头文件:
$javah -jni com.Thundersoft.hellothundersoft.MainActivity
在工程src目录下生成一个com_Thundersoft_hellothundersoft_MainActivity.h文件
在头文件com_Thundersoft_hellothundersoft_MainActivity.h
中,会有一个函数声明:
JNIEXPORT
jstring JNICALL
Java_com_Thundersoft_hellothundersoft_MainActivity_hello
(JNIEnv*, jobject);
该函数的实质就是:
1)JNIEXPORT声明该接口为动态库导出接口。
2)JNICALL声明了函数参数的入栈方式。
3)函数名为包名+类名+native方法名。
4)函数参数,每个函数都会额外添加两个参数:JNIEnv
*,jobject或者jclass(static native方法时)。
5、native方法的实现
将工程jni目录下的HelloThundersoft.cpp重命名为HelloThundersoft.c,同时将Android.mk里的LOCAL_SRC_FILES
:= HelloThundersoft.cpp
改为LOCAL_SRC_FILES
:= HelloThundersoft.c
这里用c#语言实现,在HelloThundersoft.c编写以下代码:
#include <jni.h>
#include <stdio.h>
//从头文件拷取函数声明并加上参数
JNIEXPORT jstring JNICALL Java_com_Thundersoft_hellothundersoft_MainActivity_hello(JNIEnv *
env, jobject obj)
{
char* cstr = "hello Thundersoft";
//jstring (*NewStringUTF)(JNIEnv*, const char*);
jstring jstr = (*env)->NewStringUTF(env, cstr);
return jstr;
}
在编写c代码之前,需配置头文件路径:点击工程项目->Preferences->C/C++ General->Code Analysis->Path and Symbols
点击Add,增加inludes路径.../android-ndk-r10c/platforms/android-18/arch-arm/usr/include
6、编译工程生成native库,运行该工程项目
编译工程项目:build progect,或RunAs->Android Application,
会在libs目录下生成armebi目录,armbi目录存放着native库libHelloThundersoft.so
部署工程项目,进入界面后点击按钮,会出现toast弹窗,弹窗信息是从native库