上善若水

导航

 

1、下载NDK,地址http://developer.android.com/tools/sdk/ndk/index.html。下载完后解压即可。这里到目录/work/NDK/android-ndk-r4b/

  配置NDK环境变量 

  vim ~/.bashrc或vim /etc/profile(fedora16)

  在文件尾追加

  NDK=/work/NDK/android-ndk-r4b/

  export PATH=$PATH:$NDK

  保存环境变量

  sourch  ~/.bashrc (source /etc/profile)

  查看是否配置成功

  进入NDK 的例子目录samples/hello-jni 运行ndk-build,结果如下  

  make: Entering directory `/work/NDK/android-ndk-r8d/samples/hello-jni'
  Gdbserver : [arm-linux-androideabi-4.6] libs/armeabi/gdbserver
  Gdbsetup : libs/armeabi/gdb.setup
  Install : libhello-jni.so => libs/armeabi/libhello-jni.so
  make: Leaving directory `/work/NDK/android-ndk-r8d/samples/hello-jni'

2、打开eclipse,新建工程名为TestJNI。在activity中添加以下代码

package com.example.testjni;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView textView =(TextView) findViewById(R.id.text);
        
        testJNI testJNI = new testJNI();
        textView.setText(testJNI.hello());
    }
}

  新建类TestJNI,用于调用JNI接口

package com.example.testjni;

public class testJNI {
    public native String hello();
    static{
        System.loadLibrary("testJNI");
    }
}

  完成后编译工程,bin目录生成 *.class文件

3、在工程目录先新建jni目录,到jni目录下通过javah命令生成c/c++的文件头

  javah -classpath ../bin/classes com.example.testjni.testJNI

  运行后会在jni目录下生成.h文件 com_example_testjni_testJNI.h

4、根据.h文件编写.c文件

#include <string.h>
#include <jni.h>

jstring Java_com_example_testjni_testJNI_hello( JNIEnv* env,jobject thiz )
{
    return (*env)->NewStringUTF(env, "Hello from JNI!");
}

5、编写mk文件,可从sample例子中拷贝一份,稍作修改即可,这里主要改两个地方,

  LOCAL_MODULE是描述模块的,用来给java调用的模块名,会生成对应的libtestJni.so

  LOCAL_SRC_FILES就是源文件啦,多个文件空格隔开即可。

# 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    := testJNI
LOCAL_SRC_FILES := com_example_testjni_testJNI.c

include $(BUILD_SHARED_LIBRARY)

6、编译生成.so文件

  进入工程目录下,运行$NDK/ndk-build

  注意。编译so文件的时候,可能会出现/work/NDK/android-ndk-r8d/build/gmsl/__gmsl:512: *** non-numeric second argument to `wordlist' function: ''.  Stop.错误,先把工程目录下的AndroidManifest.xml 文件删除后在编。

7、完成以上步骤之后就可以运行工程了。

  

 

  

posted on 2013-01-10 10:53  chenjinying  阅读(954)  评论(0编辑  收藏  举报