Hello World Example Using NDK in Android

Introduction : 

Android SDK ! (Wow its great. Google is serving the best as per its habit 🙂 ). But how about some native code development.Yes google Android SDK also provides facility to let their developer develop code in native language. (Most of the cases C/C++).Android NDK (Native Development Kit) simplifies the task.

Well I will explain you how to create a simple application (I use the word simple so it must be Hello World 😉 ).Follow the below given steps to deploy your first native code in Android.

1) Needed tools : Android SDK, Android NDK, Eclipse, Linux shell (If using windows).

2) Get that things installed on your work station. Installation Guide 

3) Create a project in Eclipse named HelloWorld.

4) Create a folder jni in your project directory. HelloWorld/jni

JNI (Java Native Interface) is the utility which allows us to write native code.

5) Replace your main.xml file to this.

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:gravity=”center”
>
<TextView
android:id=”@+id/txtHello”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:gravity=”center”
android:textSize=”20dip”
>
</LinearLayout>

5) Open your .java file and write following lines of code. and build the project.

package com.testndk;

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

public class HelloWorld extends Activity
{
TextView txtHello;

static
{
System.loadLibrary(“HelloWorld”);
}

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
txtHello=(TextView)findViewById(R.id.txtHello);
txtHello.setText(messageFromNativeCode());
}

public native String messageFromNativeCode();

}

6) Create a header file.

Its time to do some stuff on terminal.

Go to your bin directory using cd command

run following commands

  • javah com.testndk.HelloWorld and
  • mv com_testndk_HelloWorld.h ../jni/

This will create a header file in jni folder of your project.There will be some auto generated code in your header file. having a close look at the content of header file, you can see that the method name which we have defined in our .java file as a native method is converted in a C language compatible form.

7) Write code in C

Now we need to write a body for the function which is declared in header file, which will be something like this.

#include “com_testndk_HelloWorld.h”

JNIEXPORT jstring JNICALL Java_com_testndk_HelloWorld_messageFromNativeCode

(JNIEnv * env, jobject jObj)
{

return (*env)->NewStringUTF(env, “Hello World!”);

}

We need to return a string from the function so written type will be jstring.

  • env is a JNIEnv kind of pointer and second argument is just a simple text which we want to return.

8) Create Android.mk file

Create it in your jni folder. <project-name>/jni/Android.mk

Android.mk file is written to describe your source to the build system. System internally parses this file for various number of times for its own purpose.

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := HelloWorld
LOCAL_SRC_FILES := helloworld.c

include $(BUILD_SHARED_LIBRARY)

9) Compile the file.

Now if you have put your project in Android NDK’s repository than on terminal go to the project directory and type ../ndk-build

If you are maintaining separate workspace than copy your project to Android NDK repository. On terminal change your current directory to your project name folder.

If everything works fine you will get a following output.

You will get two folders generated named libs and obj you can explore that folder and you will find that <filename>.so file is created.This file is source file which System.loadLibrary(“”) will use.

10) Final Output

Build the project and run it on emulator.

You will have a below given output,and with this output we are done with our first NDK exmple.

Creating an HelloWorld Program in any technology is always an easy task 😉 😉 😉

Keep visiting for new tutorials on NDK.

36 thoughts on “Hello World Example Using NDK in Android

  1. hi hardik i wanna create an app in android as well as in iphone as a designer i can design it need ur help in coding if ur able to work on it then we shall discuss further on it. the concept is ready

  2. Hi,
    It is an excellent Android NDK “Hello Word” example. Is Linux shell is necessary for this example? Can this be done without linux shell, if we use Windows?

    1) Needed tools : Android SDK, Android NDK, Eclipse, Linux shell (If using windows).

    1. Hi Malik,

      It is possible in on Windows too. MacOS or Linux is easy to use as they do hav inbuilt support for C/C++ and other required things. Here I found very good tutorial for performing NDK in windows.

      Thanks for visit 🙂

  3. Can you please update this part:

    run following commands

    javah com.testndk.HelloWorld and
    mv com_testndk_HelloWorld.h ../jni/

    I get the following error:

    MacBook-Pro-de-XXXX:bin xxxx$ sudo javah com.testndk.HelloWorld
    error: cannot access com.testndk.HelloWorld
    class file for com.testndk.HelloWorld not found
    javadoc: error – Class com.testndk.HelloWorld not found.
    Error: No classes were specified on the command line. Try -help.

    My bin folder looks like:

    bin/
    —>AndroidManifest.xml
    —>classes/
    ——>com/
    ———>testndk/
    ————>BuildConfig.class
    ————>HelloWorld.class
    ————>R.class
    ————>R$attr.class
    .
    .
    .
    ————>R$style.class
    ——>res/

    The trick is not to run the command as specified on the bin folder, but in the bin/classes folder. thanks.

      1. In the console, executing javah your.package.YourClassName you will get this error if the android project doesn’t have the old dir configuration:

        error: cannot access com.testndk.HelloWorld
        class file for com.testndk.HelloWorld not found
        javadoc: error – Class com.testndk.HelloWorld not found.
        Error: No classes were specified on the command line. Try -help.

        1. In new Android you need to execute same command from bin/classes.
          So command will be something like this.
          cd bin
          cd classes
          and then javah -jni com.testndk.HelloWorld

          Please note the switch -jni I have used.

          1. Nope, that doesn’t help one bit. The exact same error. And I’ve copied everything from your example, including the classpath, to be 100% certain.

            1. Hi Frank,
              Using Mac or windows ? Windows you need to go to the android-sdk folder and then give full path of project directory.

              1. I found the error. It seems that it’s not possible to create a header file from a Java class which implements or extends Activity, AsyncTask or something else. Looks like the Java class implementing the native functions has to be a “clean” class?

  4. I found the error. It seems that it’s not possible to create a header file from a Java class which implements or extends Activity, AsyncTask or something else. Looks like the Java class implementing the native functions has to be a “clean” class?

    1. Frank has able to correct his mistake. Can you please tell me what exact problem you are facing. What error trace you are getting on console ?

  5. Hi Hardik
    Getting this error log on command line…

    C:\Android_Development_Environment\Eclipse_Juno_4.2\Juno_Workspace\GaneshNDKTest
    \bin>javah -jni com.example.ganeshndktest.MainActivity
    error: cannot access com.example.ganeshndktest.MainActivity
    class file for com.example.ganeshndktest.MainActivity not found
    javadoc: error – Class com.example.ganeshndktest.MainActivity not found.
    Error: No classes were specified on the command line. Try -help.

    1. Also Tried with ……\bin\classes

      C:\Android_Development_Environment\Eclipse_Juno_4.2\Juno_Workspace\GaneshNDKTest\bin\classes>javah -jni com.example.ganeshndktest.MainActivity
      error: cannot access com.example.ganeshndktest.MainActivity
      class file for com.example.ganeshndktest.MainActivity not found
      javadoc: error – Class com.example.ganeshndktest.MainActivity not found.
      Error: No classes were specified on the command line. Try -help.

      1. Using Windows or mac ? There will come lot of troubles using windows. Need to set up cygwin and then you can perform NDK test.

  6. Bro..i do not nothing about NDK.. how to set up NDK. for C or C ++ programs.. Can you give me any link about it.

  7. Very simple tutorial thank you so much for posting jni tutorial. Please edit:

    run following commands
    javah -jni com.officebrain.androidjnidemo.MainActivity
    Find bin/classes directory from explorer
    – copy .h (Header file) and past into jni directory

  8. hello
    getting error please help
    i use cd bin
    cd classes

    Error: cannot access android.app.Activity
    class file for android.app.Activity not found

    -jni com.example.ndkdemo.MainActivity

  9. HI Hardik Nice blog …
    Can you please let me know what extra flag we need to add in android.mk to make compatible with mac os. when i try to run command like idk-build it gives an error Like :: internal error in do_print_to_mapfile, at.

    i already did this in past but i hardly remember that if you have any idea please share it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s