ubuntu ADT 搭建NDK开发环境

前提,你已经在ubuntu下搭建了基于ADT的应用开发环境,并且可以正常开发纯java的android应用程序。

下面这些步骤,实际完成的效果和 在控制台进入jni目录执行ndk-build然后把生成的so拷贝到libs/armeabi 目录下是一样的。


首先要下载ndk。然后把ndk-build配置到环境变量。

代码:

1.新建android应用程序

2.

package com.example.android.simplejni;

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

public class SimpleJNI extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv = new TextView(this);
        int sum = Native.add(2, 3);
        tv.setText("2 + 3 = " + Integer.toString(sum));
        setContentView(tv);
    }
}

class Native {
    static {
    	// The runtime will add "lib" on the front and ".o" on the end of
    	// the name supplied to loadLibrary.
        System.loadLibrary("simplejni");
    }

    static native int add(int a, int b);
}

3.新建jni目录,Android.mk


LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE_TAGS := samples

# This is the target being built.
LOCAL_MODULE:= libsimplejni


# All of the source files that we will compile.
LOCAL_SRC_FILES:= \
  native.cpp

# All of the shared libraries we link against.
LOCAL_SHARED_LIBRARIES := \
	libutils

# No static libraries.
LOCAL_STATIC_LIBRARIES :=

# Also need the JNI headers.
LOCAL_C_INCLUDES += \
	$(JNI_H_INCLUDE)

# No special compiler flags.
LOCAL_CFLAGS +=

include $(BUILD_SHARED_LIBRARY)

native.cpp onLoad中动态注册
#define LOG_TAG "simplejni native.cpp"
#include <utils/Log.h>

#include <stdio.h>

#include "jni.h"

static jint
add(JNIEnv *env, jobject thiz, jint a, jint b) {
int result = a + b;
    ALOGI("%d + %d = %d", a, b, result);
    return result;
}

static const char *classPathName = "com/example/android/simplejni/Native";

static JNINativeMethod methods[] = {
  {"add", "(II)I", (void*)add },
};

/*
 * Register several native methods for one class.
 */
static int registerNativeMethods(JNIEnv* env, const char* className,
    JNINativeMethod* gMethods, int numMethods)
{
    jclass clazz;

    clazz = env->FindClass(className);
    if (clazz == NULL) {
        ALOGE("Native registration unable to find class '%s'", className);
        return JNI_FALSE;
    }
    if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
        ALOGE("RegisterNatives failed for '%s'", className);
        return JNI_FALSE;
    }

    return JNI_TRUE;
}

/*
 * Register native methods for all classes we know about.
 *
 * returns JNI_TRUE on success.
 */
static int registerNatives(JNIEnv* env)
{
  if (!registerNativeMethods(env, classPathName,
                 methods, sizeof(methods) / sizeof(methods[0]))) {
    return JNI_FALSE;
  }

  return JNI_TRUE;
}


// ----------------------------------------------------------------------------

/*
 * This is called by the VM when the shared library is first loaded.
 */
 
typedef union {
    JNIEnv* env;
    void* venv;
} UnionJNIEnvToVoid;

jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
    UnionJNIEnvToVoid uenv;
    uenv.venv = NULL;
    jint result = -1;
    JNIEnv* env = NULL;
    
    ALOGI("JNI_OnLoad");

    if (vm->GetEnv(&uenv.venv, JNI_VERSION_1_4) != JNI_OK) {
        ALOGE("ERROR: GetEnv failed");
        goto bail;
    }
    env = uenv.env;

    if (registerNatives(env) != JNI_TRUE) {
        ALOGE("ERROR: registerNatives failed");
        goto bail;
    }
    
    result = JNI_VERSION_1_4;
    
bail:
    return result;
}


4. 如果提示 ,去掉 #include <utils/Log.h> 

[armeabi] Compile++ thumb: simplejni <= native.cpp
jni/native.cpp:18:23: fatal error: utils/Log.h: No such file or directory
 #include <utils/Log.h>
                       ^
compilation terminated.
make: *** [obj/local/armeabi/objs/simplejni/native.o] Error 1

android JNI utils/Log.h 找不到
在JNI的c文件中如果用到了#include <utils/Log.h>

然后用NDK 编译, ndk-build clean && ndk-build 提示error: utils/Log.h: No such file or directory

如果只是用到LOG功能

1 修改Android.mk文件配置,添加如下语句

LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -llog

2  在.c文件中修改为如下语句

//#include <utils/Log.h>//  关闭此行

#include<ALog.h>//增加些行

3  ALog.h 文件内容如下:

#pragma once

#include<android/log.h>

#define ALOG_TAG "debug log"
#define ALOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, fmt, ##args)
#define ALOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, fmt, ##args)
#define ALOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, fmt, ##args)

4----可以使用Log输出信息,同Java层的 Log.i
ALOGI("jni android log!!!!")

ALOGD("the string is: %s \n", strMsg);

ALOGE(strerror(errno))

方法一:


Setting up Automatic NDK Builds in Eclipse

When editing native JNI code in an Android project using the Android NDK you may configure Eclipse to automatically rebuild your project when editing native code, just as it does for java. The below steps shows how to perform the necessary configuration (note that this requires revision 4 or later of the NDK - previous revisions does not contain the necessary ndk-build binary):

Start by right clicking on your android project (named hello-neon in the below screenshots) with JNI resources, and select Properties. In the resulting dialog, choose the Builders entry in the list to the left and press the New... button:

ubuntu ADT 搭建NDK开发环境_第1张图片

A new dialog will open presenting a list of builder types. Select the Program type and press the OK button:

In the Main tab, fill in the following:

Name:
NDK Builder
Location:
/opt/android-ndk/ndk-build (or wherever your ndk-build binary is). You may use a variable as in ${system_property:user.home}/lib/android-ndk/ndk-build
Working Directory:
${workspace_loc:/hello-neon} (replace hello-neon with your project name. Press the  Browse Workspace... button to select it graphically)

The result should look something like the below:

Now continue with the refresh tab. Make sure the two checkboxes Refresh resources upon completion. and Recursively include sub-folders are checked. Choose the Specific resources radio button and press the Specify Resources... button:

ubuntu ADT 搭建NDK开发环境_第2张图片

Since the ndk-build process will generate files in the lib folder, we want Eclipse to discover changes made there without having to refresh manually. So select the lib folder in the project (create one if necessary) and press the Finish button:

Now skip the Environment tab and go to the final Build Options tab. Make sure the Run the builder: During auto builds checkbox is checked.

ubuntu ADT 搭建NDK开发环境_第3张图片

Since the NDK build only needs to happen when editing files in the jni folder, check that folder and press theFinish button.

ubuntu ADT 搭建NDK开发环境_第4张图片

Now finally press OK in the builder configuration dialog - the new NDK builder should now be up and running. Try editing any file in the jni folder and check that the Console view produces output from the build process:

ubuntu ADT 搭建NDK开发环境_第5张图片

 


方法二:

Installation

To install and configure the NDK, follow these steps:

  1. Get and install the Android SDK.
  2. Download and extract the NDK, making sure to download the correct version for your development platform. You may place the unzipped directory anywhere on your local drive.
  3. Update your PATH environment variable with the location of the directory that contains the NDK.

Configuring Eclipse

Eclipse must know where the NDK is in order to use it when building your app. Follow these steps to set the location of the NDK.

  1. Launch Eclipse, which is installed as part of the Android SDK.
  2. Open Window > Preferences.
  3. In the pane on the left side of the Preferences window, select Android. The Android section expands, revealing a number of subsections.
  4. Select NDK. In the pane on the right side of the Preferences window, browse to the directory that contains the NDK.
  5. Click OK to return to the Package Explorer display.

Verification

Eclipse

To confirm that you have installed the NDK, set it up correctly, and properly configured Eclipse, follow these steps:

  1. Import the hello-jni sample from <ndk>/samples/, as you would any other Android project.
  2. In the Project Explorer pane, right-click the project name (HelloJni). A context menu appears.
  3. From the context menu, select Android Tools > Add Native Support. The Add Android Native Supportwindow appears.
  4. Accept the default library name (“hello-jni”), and click Finish.
  5. Build and execute the application.

Command line

Follow these steps to build from the command line:

  1. Change to the root directory of your project.
  2. Execute ndk-build to build the native component of your app. do this by typing ndk-build at the command prompt.
  3. Build and install your project as you would a regular Android app written in Java. For more information, seeBuilding and Running and Building and Running from the Command Line.



你可能感兴趣的:(ubuntu ADT 搭建NDK开发环境)