今天试着在Ubutnu环境下,编写了一个NDK的helloworld的程序,并在此归纳总结想下:
1.首先建一个Android Project工程,并创建一个类,如下:
package com.android.study; public class DemoTest { static { System.loadLibrary("DemoTest"); } public native String helloWord(); }
3. 在项目根目录下面新建jni文件夹,并使用javah 工具 生成对应的.h
进入项目的/bin/classes 目录下,然后运行如下命令:
javah -classpath . -jni com.android.study.DemoTest
javah -classpath bin/classes -d jni com.android.study.DemoTest
sudo ln -s '/usr/local/java/jdk1.6.0_31/bin/javah' /usr/bin/javah
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_android_study_DemoTest */ #ifndef _Included_com_android_study_DemoTest #define _Included_com_android_study_DemoTest #ifdef __cplusplus extern "C" { #endif /* * Class: com_android_study_DemoTest * Method: helloWord * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_android_study_DemoTest_helloWord (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif4.编写.c文件
#include <string.h> #include <jni.h> jstring JNICALL Java_com_android_study_DemoTest_helloWord (JNIEnv *env, jobject object) { return (*env)->NewStringUTF(env, "Hello world JNI !"); }
# Copyright (C) 2009 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := DemoTest LOCAL_SRC_FILES := demo.c include $(BUILD_SHARED_LIBRARY)
6 在项目根目录下面运行ndk-build 生成相应的.so文件
7.在相应的Activity 中调用并显示出来
package com.android.study; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; public class JniDemoActivity extends Activity implements OnClickListener { private TextView mContenTextView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mContenTextView = (TextView) findViewById(R.id.tv_content); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_submit: DemoTest test = new DemoTest(); mContenTextView.setText(test.helloWord()); break; default: break; } } }