如何在android项目中使用NDK?

时间:2010-12-05 16:12:28

标签: c++ android c java-native-interface android-ndk

我需要在我的项目中使用一些本机c / c ++,所以我需要使用NDK。有没有一种简单的方法在eclipse中设置它?

感谢。

2 个答案:

答案 0 :(得分:14)

有以下步骤

1:在项目目录中创建 jni 文件夹

2:在新创建的文件夹 jni 中创建文件名 Android.mk 并创建新的C或C ++文件,让我们考虑听听我们使用C文件和文件名是MyNativeC.c

3:现在在Android.mk文件中键入以下代码

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_LDLIBS := -llog

LOCAL_MODULE    := local_module_ndk // this is the name of local module by which you can call the Local source file
LOCAL_SRC_FILES := MyNativeC.c// hear we can pass the name of your native file name hear we are use MyNativeC.c file so we pass the name of MyNativeC.c in local source file name

include $(BUILD_SHARED_LIBRA

4现在打开MyNativeC.c文件并创建两个你想从你的android代码调用的方法(来自你的Activity)  听说我们创建以下代码

    #include <jni.h>
#include <string.h>
#include <stdio.h>
#include <android/log.h>

#define DEBUG_TAG "MY_NDK_DEMO"


jstring Java_com_myNDKDemo_MainActivity_getString(JNIEnv * env, jobject this, jint value1, jint value2)
{
    char *szFormat = "Addition : %i";
    char *szResult;


    jlong sum = value1+value2;


    szResult = malloc(sizeof(szFormat) + 20);


    sprintf(szResult, szFormat, sum);

    jstring result = (*env)->NewStringUTF(env, szResult);


    free(szResult);

    return result;
}

5现在编辑您想要调用本机代码的活动

首先创建一个静态块,我们必须加载本机代码库。

听说我们显示我的活动名称的代码是MainActivity.java

package com.myNDKDemo

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {
    private static final String DEBUG_TAG = "MainActivity";


    private native String getStringAdd(int fist, int second);

    static {
        System.loadLibrary("local_module_ndk");
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        button b = new Button(this);

        b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


                            Toast.makeText(getApplicationContext(),""+getStringAdd(100,200), 2000).show();

        }
    });

           setContentView(b);

    }
}

6现在首先编译c代码,首先编译c代码,你必须NDK development kit

现在开放运行。并键入cmd

现在转到项目路径

In my case I create application in Destop, so hear we give the path of my app

之后我的NDK的ndk-build文件路径的路径

enter image description here

现在我们按下输入自动它在你的项目中创建libs目录 enter image description here

7如果您在项目中看到,则会自动创建 libs和obj

8.Refresh(右键单击)JNI文件夹(每次使用teh ndk-build构建时刷新它,这实际上会在libs文件夹中加载新构建的共享库。)

9.现在运行你的android项目,按下按钮它会显示添加

谢谢

答案 1 :(得分:4)

好的,在我花了一些时间进行实验之后,我可以说初学者在eclipse中开始使用NDK的最好方法是首先阅读本教程:http://marakana.com/forums/android/examples/49.html并简单地为jni创建必要的文件文件夹(但不做任何其他事情)。然后,您应该阅读此http://mobilepearls.com/labs/ndk-builder-in-eclipse/并按照步骤操作。那你就准备好了。