复习Android NDK ,HelloWorld 作例子
上马::
1、创建一个Android Project
2、其中的 MainActivity 的代码:
package biz.inspeed.hello; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { static { System.loadLibrary("HelloWorld"); } private TextView mTextView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupViews(); setContents(); } private void setContents() { this.mTextView.setText(this.getStringFromNative()); } private void setupViews() { this.mTextView = (TextView) this.findViewById(R.id.text); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public native String getStringFromNative(); }
4、用终端进入到 workspace/HelloJNIAndroid/bin/classes 目录,
javah biz.inspeed.hello.MainActivity得到头文件
5、将头文件mv到jni目录里面
mv classes/biz_inspeed_hello_MainActivity.h ../jni/6、创建一个c 文件,实现native方法
#include <string.h> #include "biz_inspeed_hello_MainActivity.h" JNIEXPORT jstring JNICALL Java_biz_inspeed_hello_MainActivity_getStringFromNative (JNIEnv *evn, jobject obj) { return (*evn)->NewStringUTF(evn, "Hello from JNI !"); }
编写Android.mk(也在jni目录里面):
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := HelloWorld LOCAL_SRC_FILES := hello.c include $(BUILD_SHARED_LIBRARY)
LOCAL_SRC_FILES 是要编译的源代码
7、将整个Project 拷贝到ndk的home目录
8、在终端中cd到Project 目录
9、编译c代码 得到类库文件
../ndk-build10、在project会得到一个libs目录,将目录里面的文件件拷贝到 eclipse项目中的libs目录就可以运行了。
参考链接:http://trivedihardik.wordpress.com/2011/06/16/hello-world-example-using-ndk-in-android/
<全文完>