December 30, 2011

Android NDK JNI Windows xp/7 with 32/64 bit Installation Problems with Solutions in Eclipse without C/C++ CDT Plugin

Hi all,

I spent 2 days on configuring this. I read lot of blogs and instrutction steps from various sites. I would like share my experience on installing Android NDK and Working with Eclipse.

Objective:
Using JNI Technology in Eclipse with Android NDK r6/r7 on Windows xp/7 Professional

Pre-requirements:
  1. Java SE SDK -- Java Development Kit
  2. Eclipse Helios/Indigo -- IDE to work with Java, Android, C/C++ etc.
  3. Android SDK -- Android Applications Development Kit
  4. Android ADT Plugin for Eclipse -- Download the latest Android SDK Platform Tools
  5. C/C++ Plugin for Eclipse (Optional) -- Make sure that .c, .cpp, .h files opening from Eclipse
  6. Android NDK (r6/r7) -- Native development i.e. Running c libraries in Android
  7. Cygwin 1.7.x or above -- Makefile creation, Library file creation tools, Compiling C files

Installation:
  1. Install the Java Development Kit
  2. Install the Android SDK and ADT Plugin with Eclipse
  3. [Optional] Install CDT plugin for Eclipse
  4. Download and extract the Android NDK
  5. Install Cygwin 1.7.x or above
Note: Don't extract in a folder where folder name is having spaces in between words.
Example:
"Program Files" -- Don't Use
"ProgramFiles" -- Use

Configuration:
Please make sure that you have set the environment variables like
  • JAVA_HOME -- Java Home Directory
  • NDK_HOME -- Android NDK Home Directory
  • Update Path Variable with JDK Bin folder
Creating Android Application
  • In Eclipse, Select File->New->Android Project
  • Enter the Project Name and Click on "Next" button
  • Select the "Build Target", I opted for Android 2.2, SDK 8 Version and Click on "Next" button
  • In Application Info dialog, enter the "Package Name" and Select "Finish" button
  • Now, you can see the newly created SampleNDK project in the eclipse project explorer window

Example:
  • Eclipse Workspace Folder: D:\Workspace
  • Android Application Name: SampleNDK
  • Android Application Working Folder: D:\Workspace\SampleNDK
  • Package Name: com.samplendk
  • Android Application Source Folder: D:\Workspace\SampleNDK\src

Source of AndroidNDKActivity.java
package com.samplendk;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;

public class SampleNDKActivity extends Activity {
   
    //Declare the native method
    private native String invokeNativeFunction();
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        //Call the native methods
        String hello = invokeNativeFunction();
        new AlertDialog.Builder(this).setMessage(hello).show();
    }
   
}

  • Create a folder named "jni" in the project
    • Right click on the "SampleNDK" project-> Select "New"-> Select "Folder"->Type "jni"
  • Create files "Android.mk" and "native.c" in Jni folder
    • Right click on the "jni" folder-> Select "New"-> Select "File"->Type "Android.mk"
    • Right click on the "jni" folder-> Select "New"-> Select "File"->Type "native.c"
  • After Creating those folder and files, the project explorer window look like this
  • Do some continuous steps.
    • Build, Refresh, and Clean project
      • Right Click on the "SampleNDK" project and Select the "Build Project"
      • Select "Sample NDK" project and Click "F5" button on keyboard
      • Select "Project" menu and Select "Clean" option

  • Create header file of the java file
    • In windows command prompt, change to project source directory
    • Syntax:
      • cmd>
      • cmd> cd ProjectDir/src

    • Example:
      • cmd> D:
      • D:\> cd SampleNDK/src
    • Run the Javah command to create header file
    • Syntax:
      • cmd> javah -jni .javafile_without_.java_extension // JDK 1.7
      • cmd> javah -classpath ..\bin\classes .javafile_without_.java_extension //JDK1.6
    • Example:
      • D:\SampleNDK\src> javah -jni com.samplendk.SampleNDKActivity //JDK1.7
      • D:\SampleNDK\src> javah -classpath ..\bin\classes com.samplendk.SampleNDKActivity //JDK1.6
    • Note:
      • Don't include the .java at the end of javah command

  • Copy the created java header file to jni folder
    • D:\SampleNDK\src> copy com_samplendk_SampleNDKActivity.h ..\jni

  • Go to Eclipse and Refresh the project by pressing "F5" on keyboard.
  • Open the header file from jni folder
  • Copy the function created by javah as shown below
  • Paste the code in native.c and change the code similar to this
Source of native.c
#include <string.h>
#include "com_samplendk_SampleNDKActivity.h"

jstring JNICALL Java_com_samplendk_SampleNDKActivity_invokeNativeFunction
  (JNIEnv *env, jobject obj)
{
    return (*env)->NewStringUTF(env, "Hello from native function !!");
}

Source of Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# Here we give our module name and source file(s)
LOCAL_MODULE := SampleNDK
LOCAL_SRC_FILES := native.c

include $(BUILD_SHARED_LIBRARY)

  • Run Cygwin.bat file in the Cygwin installed directory
  • It will open the cygwin command prompt
  • Change the directory to SampleNDK project directory
    • Note: All the drives in your systems are mounted to some directory in the cygwin.
    • To see your drive mount points type mount
    • # mount
  • # cd /cygdrive/d/SampleNDK/
  • Run the ndk-build command from the android ndk directory
    • # /cygdrive/d/android-ndk-r7/ndk-build

  • Error(Only in Android-ndk-r7):
  • You may get some error like the following
    • /awk.exe: can't open file check-awk.awk
    • Andoid NDK: Host 'awk' tool is outdated. Please define
    • HOST-Awk to Point to Gawk or Nawk !
  • Resolution:
    • Goto the android-ndk/prebuilt/windows/bin/
    • Change the awk.exe to awk_.exe

  • Now you may see the following output after successful execution
  • After successful creating libSampleNDK.so file, refresh your Eclipse project
  • You can see the updated "Project Explorer" with "libs" folder in the tree hierarchy
  • Update the java source code now by adding this library to it
Source code of SampleNDKActivity.java
package com.samplendk;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;

public class SampleNDKActivity extends Activity {
   
    static
    {
        System.loadLibrary("SampleNDK");
    }

   
    //Declare the native method
    private native String invokeNativeFunction();
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        //Call the native methods
        String hello = invokeNativeFunction();
        new AlertDialog.Builder(this).setMessage(hello).show();
    }
   
}

  • Clean the project by Selecting "Project"->"Clean"
  • Run the application as "Android Application"
  • Note:
    • Error:
      • java.lang.unsatisfiedLinkError Library -- not found
    • Resolution:
      • Please see if you have added the "lib" in java source before adding the library in System.loadLibrary() method
  • Please find the screenshot of above running program in emulator


If you have queries, please mail to psrdotcom@gmail.com

15 comments:

Alessio said...

Thank you for the Tutorial. But I have some problems in the #include.
As in your screenshots, I get (E.g.) "Unresolved inclusion: ".
Therefore as I run ndk-build in cygwin, it returns errors and the *.so file cannot be generated.
Moreover, if I wanted to create my native code (cpp) and call the functions from java-android and passing parameters (from EditText in layout), which would be the steps for implementing this features? I really cannot find anything about this and I am really in troubles. I am reading the JNI docs, but I cannot find the solution.
I am using Eclipse with C/C++ support, SDK, ADT plugin, NDK 7, CygWin.

Alessio said...

UPDATE:

I found the error and corrected it. I finally installed the application on the emulator. Now the problem is that it cannot run "unexpected error - force close".

Suresh Raju Pilli said...

Please send the DDMS log to mail. May be some linking issue.

Alessio said...

Hi Suresh, I just sent youi the DDMS log by email.
Please, keep me update and thank you in advance for your help.

Suresh Raju Pilli said...

Hi Alessio,

1. You can use your own c++ code by putting it in JNI folder.
2. You can pass java empty strings, stringbuffers to get the content loaded in it from a c/c++ program and you can use the filled string, stringbuffer in java(Edittext data).

http://java.sun.com/docs/books/jni/download/jni.pdf

Avatar Html5 Player said...

Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write ups thanks once again.
Avatar Html5 Video Player

Assem Ali said...

Actually i am having a error while trying to create the header file (*.c) when i type the command (Java version 1.7.0_03-b05)i get this{
error:cannot access com.samplendk.SampleNDKActivity call file for com.samplendk.SampleNDKActivity not found
javadoc: error - Class com.samplendk.SampleNDKActivitynot found
Error: no classes were specified on the command line Try -help}
thank you in advance

Suresh Raju Pilli said...

You must be in the source directory of the project while running the command to create a header file. Please see the directory while executing the header file creation.

NJDev said...

I am having trouble getting started in the very beginning. I am not sure how to set the environment variables you talk about. I can open the Environment Variables window on my computer, but don't know exactly what to do with them. Thank you for your time.

Suresh Raju Pilli said...

Hope this link will solve your problem.
http://java.com/en/download/help/path.xml

Suresh Raju Pilli said...

http://wso2.org/project/wsas/java/1.1/docs/setting-java-home.html

http://docs.oracle.com/javase/tutorial/essential/environment/paths.html

Sanjay Barfa said...

i am beginner
i'm having a hell of a time importing OpenCV into my Android project. I've already tried this tutorial:

http://opencv.itseez.com/doc/tutorials/introduction/android_binary_package/android_binary_package.html

and it did not work because Eclipse would not recognize the existing projects in the directory. So after much searching I came across this trunk:

https://github.com/billmccord/OpenCV-Android

and was able to import it into my workspace in Eclipse. Eclipse now recognizes the sample projects, but now the problem is that there are no OpenCV library files. So all the calls to import different classes result in errors.How Can I built NDK Inside This Apps . I'm running Windows 7 32-bit.

Thanks!

kannan radhakrishnan said...

Hello sir i want guide when automatically download and install android app(apk.file)
plz help me

ravindra said...

Hello
Thanks for great writing..

Is this process same process to install NDK for cocos2d-x game devlopment

Suresh Raju Pilli said...

I hope it will be more over same procedure.

Amazon Deals

Watches Offers from Amazon

Popular Posts

PSR Followers

Share