Android学习期间,写下来做为例子保存。
1. Eclipse中新建Android工程
- 工程名 JNItest
- Package名com.ura.test
- Activity名 JNItest
- 应用程序名 JNItest
2. 编辑main.xml
< ?xml version="1.0" encoding="utf-8"?> < LinearLayout xmlns:android="http://schemas.Android.com/apk/res/Android" Android:orientation="vertical" Android:layout_width="fill_parent" Android:layout_height="fill_parent">
< TextView Android:id="@+id/JNITest" Android:layout_width="fill_parent" Android:layout_height="wrap_content" Android:text="@string/JNITest"/>
< /LinearLayout>
3. 编辑java文件
package com.ura.test; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.TextView; public class JNItest extends Activity { static { System.loadLibrary("JNITest"); } public native String GetTest(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_jnitest); String str = GetTest(); TextView JNITest = (TextView)findViewById(R.id.JNITest); JNITest.setText(str); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_jnitest, menu); return true; } }
4. 生成head文件
编译上面工程声称class文件,然后用javah工具生成c/c++头文件 (注意路径)
@uw001279:~/workspace/JNItest/bin/classes$ javah -jni com.ura.test.JNItest
5. 编写c/c++文件如下
#include "JNItest.h" #define LOG_TAG "JNITest_Native" #undef LOG #include <utils/Log.h> JNIEXPORT jstring JNICALL Java_com_ura_test_JNItest_GetTest (JNIEnv * env, jobject obj) { return (*env)->NewStringUTF(env,(char*)"JNITest Native String"); LOGD("Hello LIB!\n"); }
6. 编写Android.mk文件
LOCAL_PATH:=$(call my-dir) include $(CLEAR_VARS) LOCAL_SRC_FILES:= \ JNItest.c LOCAL_C_INCLUDES += \ $(JNI_H_INCLUDE) \ JNItest.h LOCAL_SHARED_LIBRARIES := libutils LOCAL_PRELINK_MODULE := false; LOCAL_MODULE := libJNItest include $(BUILD_SHARED_LIBRARY)
7. 编译生成动态库
(1)新建文件夹 ~/mydroid/external/libJNITest
(2)把上面编写好的头文件,c/c++源文件,make文件拷贝进上面目录中
(3) 执行
cd cd mydroid/build/ envsetup.sh cd ~/mydroid cd external/libJNITest/ mm
(4) 编译成功的后会在下面目录中生成libJNITest.so文件
out/target/product/generic/system/lib/libJNItest.so
8. 在手机中执行程序
(1) 把动态库拷进/system/lib中
adb shell
adb remount
adb push libJNITest.so /system/lib
(2) 执行java程序JNITest
(3) 会看到屏幕上打印出
JNITest Native String