(转载请注明出处:http://blog.csdn.net/buptgshengod)
1.背景
android NDK可以用来编译android的native方法,也可以将c和c++的代码编译成.so文件,让android程序运行。
2.NDK安装(linux环境)
(1)下载对应的ndk版本,在shell里输入如下命令
gedit ~/.bashrc
(2)打开bash文件,添加下载的ndk路径
NDKROOT=/home/CORPUSERS/28852262/android-ndk-r9c export PATH=$NDKROOT:$PATH
(3)输入如下命令,然后重启shell
source /etc/profile
(4)在shell中输入ndk-build,出现如下状态说明安装成功
3.jni第一个demon helloworld
(1)编写hello-jni.c文件。
#include <string.h> #include <jni.h> /* This is a trivial JNI example where we use a native method * to return a new VM String. See the corresponding Java source * file located at: * * apps/samples/hello-jni/project/src/com/example/hellojni/HelloJni.java */ jstring Java_com_example_hellojni_HelloJni_aa( JNIEnv* env, jobject thiz ) { #if defined(__arm__) #if defined(__ARM_ARCH_7A__) #if defined(__ARM_NEON__) #define ABI "armeabi-v7a/NEON" #else #define ABI "armeabi-v7a" #endif #else #define ABI "armeabi" #endif #elif defined(__i386__) #define ABI "x86" #elif defined(__mips__) #define ABI "mips" #else #define ABI "unknown" #endif return (*env)->NewStringUTF(env, "Hello from JNI ! Compiled with ABI " ABI "."); }
这个c文件实现输出一个string型函数,注意这里
Java_com_example_hellojni_HelloJni_aa我们创建android应用的时候包和函数命名要和这个对应,否则汇报错:native method is not found。如下图
(2)编写android.mk文件,我会把相关资源上传
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := hello-jni LOCAL_SRC_FILES := hello-jni.c include $(BUILD_SHARED_LIBRARY)
(3)注意文件夹名要是jni,否则ndk不识别
(4)shell中进入相关路径下面执行
ndk-build
(5)将生成的libs文件和已经编号的jni导入工程
(6)看下主程序代码,注意注释
public class HelloJni extends Activity { TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hello_jni); tv=(TextView)findViewById(R.id.textView1); Button bt2 = (Button)findViewById(R.id.button1); bt2.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { tv.setText(aa()); } }); } public native String aa();//native方法,对应c文件Java_com_example_hellojni_HelloJni_aa中的aa static { System.loadLibrary("hello-jni");//注意名字是是libhello-jni.so去掉lib和后缀 } }
(7)效果
点击按钮:出现一串话
最后把工程上传,我的工程是公司的sdk,所以大家用的时候要换成自己的。lib和jni都是通用的,have fun!
资源下载:http://download.csdn.net/detail/gshengod/7034015