第一步:創(chuàng)建一個(gè)Android project:
package com.test;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class JNITestActivity extends Activity {
TextView textView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textView);
String myString =getText();//調(diào)用native方法
textView.setText(myString);
}
static {
System.loadLibrary("mylib"); //導(dǎo)入鏈接庫
}
public native String getText();//聲明native 方法
}
第二步:創(chuàng)建文件夾jni包含兩個(gè)文件source.c(這里可以先在eclipse中安裝cdt插件:cdt - http://update./tools/cdt/releases/new)、Android.mk,。
source.c
#include <string.h>
#include <stdio.h>
#include <jni.h>
jstring
Java_com_test_JNITestActivity_getText (JNIEnv* env, jobject obj)
{
return (*env)->NewStringUTF(env, "Test Android NDK!");
}
Android.mk:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := mylib
LOCAL_SRC_FILES := source.c
include $(BUILD_SHARED_LIBRARY)
第三步:然后用cygwin編譯source.c文件(操作如下):
這時(shí)候項(xiàng)目的目錄變成了:
第四步:創(chuàng)建文件夾<project>/libs/armeabi,將obj/armeai/libmylib.so文件拷到<project>/libs/armeabi下面,。
運(yùn)行項(xiàng)目,結(jié)果如下: