本文讲解如何在Android里使用用c ,c++编写好的库
第一步:首先编写java源文件,然后编译
package com.testndkso.test;
import android.app.Activity;
public class TestNDKsoActivity extends Activity {
/** Called when the activity is first created. */
public native String StringInfo();
static //加载库
{
System.loadLibrary("testInc");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maintest);
TextView textView = (TextView) findViewById(R.id.textView1);
String tempStr = StringInfo();
textView.setText(tempStr);
System.out.println("tempStr=="+tempStr);
System.out.println(StringInfo());
}
}
第二步:转到工程所在目录,用javah生成.h文件
在Docs窗口中输入:
C:\Documents and Settings\Administrator>e:
E:\>cd E:\TestNDKso
E:\TestNDKso>javah -classpath ./bin/classes -d jni com.testndkso.test.TestNDKsoActivity
成功后我们在这个工程的目录下自动生成一个jni文件,在这个文件目录下生成了一个com.testndkso.test.TestNDKsoActivity.h的头文件,如下所示:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_testndkso_test_TestNDKsoActivity */
#ifndef _Included_com_testndkso_test_TestNDKsoActivity
#define _Included_com_testndkso_test_TestNDKsoActivity
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_testndkso_test_TestNDKsoActivity
* Method: StringInfo
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_testndkso_test_TestNDKsoActivity_StringInfo
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
com_testndkso_test_TestNDKsoActivity.h文件 (这里的文件名可以自己取)
第三步:在eclipse中这个工程的jni的目录下建一个.c文件,文件名为java源文件中加载那个库的名字,在我这个例子中就是testInc.c,编写.c程序:
#include <string.h>
#include <jni.h>
JNIEXPORT jstring JNICALL Java_com_testndkso_test_TestNDKsoActivity_StringInfo(JNIEnv *env, jobject thiz)
{
return (*env)->NewStringUTF(env, "Hello from JNI !");
}
第四步:在eclipse中这个工程的jni的目录下建一个Android.mk文件文件内容为:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := testInc
LOCAL_SRC_FILES := testInc.c
include $(BUILD_SHARED_LIBRARY)
第五步:接下来我们就可以利用Android NDK生成.so库了:
在控制台执行
C:\Documents and Settings\Administrator>e:
E:\>cd E:\TestNDKso\jni
E:\TestNDKso\jni>E:\android-ndk-r7b\ndk-build
OK!!!!!!!!