Window下使用android NDK开发Android应用-入门篇
原创文章,欢迎转载,转载时务必注明原文地址及作者
PS:新版本r6以上请参照一下方法
最新版本的NDK都是用过一个ndk-build的命令进行编译,通过一个*.mk的文件为编译的makfile文件,进入cygwin开发环境后,进入你们要编译项目的根目录执行ndk-build就可以编译了,它可以自动找到项目子目录中的*.mk文件,很方便。
对于ndk-build路径配置问题,我的做法是在windows路径配置android NDK的安装目录,cyginw就可以找到,不用配置很多路径。
访问工程目录请使用 cd /cygdriver/e/ ...
一.搭建环境
1.下载并安装Cygwin,这个安装的过程需要花费一点时间,网上教程一堆,这里就不多说啦。什么不想下载安装那就不必往下看啦。
2.设置android ndk的环境变量,在你启动Cygwin时的默认路径下寻找.bash_profile文件,如果没有,就添加一个,编辑文件内容,添加下面代码
ANDROID_NDK_ROOT=/cygdriver/e/android/android/android-ndk-1.5_r1export ANDROID_NDK_ROOT这里的路径是你的NDK解压路径,任意目录均可以。
cd $ANDROID_NDK_ROOT,呵呵,报错啦,仔细检查你的配置文件吧,配置正确的话就可以成功转到本地的NDK目录下啦
./host-setup.sh编译安装NDK本地环境
make APP=hello-jni命令编译例子,成功可以在ANDROID_NDK_ROOT/apps/hello-jni/project/libs/armeabi目录下找到一个libhello-jni.so的文件。
public class Hello {public String sayHello() {return displayHelloWorld();}private native String displayHelloWorld();}/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class com_demo_Hello */#ifndef _Included_com_demo_Hello#define _Included_com_demo_Hello#ifdef __cplusplusextern "C" {#endif/* * Class: com_demo_Hello * Method: displayHelloWorld * Signature: ()Ljava/lang/String; */JNIEXPORT jstring JNICALL Java_com_demo_Hello_displayHelloWorld (JNIEnv *, jobject);#ifdef __cplusplus}#endif#endif/* * 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. * */#include <string.h>//#include <stdio.h>#include "hello-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 *///jstringJNIEXPORT jstring JNICALL Java_com_demo_Hello_displayHelloWorld( JNIEnv* env, jobject thiz ){//printf("Hello JNI Is Run!\n"); return (*env)->NewStringUTF(env, "Hello from JNI !");}public class MainActivity extends Activity {private static final String LOG_TAG = "MainActivity";//private List<ItemDO> items; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String msg = new Hello().sayHello(); setContentView(R.layout.main); TextView messageView = (TextView)findViewById(R.id.message); messageView.setText(msg); } static { System.loadLibrary("hello-jni"); }}注意这里的System.loadLibrary("hello-jni");library名称是你make时的APP=的名称,跟生成的libhello-jni.so文件名没有任何关系。