Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to use Android Native Development Kit (NDK) for Native programming

This article describe about the Android Native Development, way to use Native Development Kit to use C/C++ classes and functions.

Native Code as the name indicate are the codes (or Application) written in C and C++. Most of the developers have developed their applications using C and C++ especially application like Antivirus requires code to be written in native languages.

In order to port or reuse previously written code in Android, it requires knowledge of Android Native Development. Using NDK and Cygwin or MinGw we can call C/C++ functions in our java code without any trouble.

In this article we will see how Android (more specifically Java) reuses C/C++ code.

Objective:

To Develop and Android App that Call or Use C/C++ code effectively.

Setup for NDK:

I assume that you have basic knowledge of Android to develop simple apps so you must have and IDE, Android SDK installed in your system. For this article I am using eclipse IDE with ADT plug-in and latest Android SDK installed.

In the same eclipse install support for C/C++ so that we can use library files that are required by C/C++, using following steps:

Go To Help-> Select Install New Software menu option.

In the Work with enter the URL “ http://download.eclipse.org/releases/galileo” without quotes and wait for some time , as soon as the tree item load, check the Eclipse C/C++ Development Tools under the Programming Languages Option. Then press next and follow the simple screen instruction to install C/C++ support. (See the Snapshots)

Shows the List of Packages after entering URL“http://download.eclipse.org/releases/galileo“. Out of which you need to expand Programming Languages option.

Figure 1: Shows the List of Packages after entering URL“http://download.eclipse.org/releases/galileo“. Out of which you need to expand Programming Languages option.

Shows the List of Packages inside the Programming Languages Option. You need to select Eclipse C/C++ Development Tools.

Figure 2: Shows the List of Packages inside the Programming Languages Option. You need to select Eclipse C/C++ Development Tools.

During installation it will give some warning, accept it.

After successfully installation restart the eclipse.

Note: you can install C/C++ manually also using link given in step b) and then using eclipse to install plug-in offline mode in Help-> Install New Software->Add then browse for the location of C/C++ package.

Next step is to download NDK from this link http://developer.android.com/tools/sdk/ndk/index.html. Download the zip file according to the OS you have and unzip it in a directory that has no space in their path. The reason why I am always saying choose directory without spaces as many developer got error just because of spaces and it is quite difficult to identify this error.

Most important and useful step is to install either Cygwin ( from http://www.cygwin.com/ )or MinGW (from http://sourceforge.net/projects/mingw/files/)

When you install Cygwin you need to do the following steps:

Download Cygwin exe and run it.(see snapshot)

Shows the Screen when you run Cygwin exe. This is the start of the installation process.

Figure 3: Shows the Screen when you run Cygwin exe. This is the start of the installation process.

Choose radio option “Install from Internet” and click next.

Shows the Screen for choosing Download Source out of three Radio Buttons

Figure 4: Shows the Screen for choosing Download Source out of three Radio Buttons.

Choose installation directory that contain no spaces as Cygwin based on Unix OS feature.

Shows the Screen for selecting Directory for installation of Cygwin.

Figure 5: Shows the Screen for selecting Directory for installation of Cygwin.

Choose any directory for storing setup files.

Shows the Screen for selecting directory where the required installation files need to keep during installation.

Figure 6: Shows the Screen for selecting directory where the required installation files need to keep during installation.

Next Choose Internet Connection type.

Shows the Screen for selecting the type of internet connection you are using or you want to use for downloading files

Figure 7: Shows the Screen for selecting the type of internet connection you are using or you want to use for downloading files.

Next choose the mirror for download (Choose any one geographically nearer to your place).

Shows the Screen for selecting the mirrors from where you want to download.

Figure 8: Shows the Screen for selecting the mirrors from where you want to download.

After you choose the mirror then click Next, Cygwin will download and present to you the list of available packages.

Shows the list of packages for installation. You can choose required packages

Figure 9: Shows the list of packages for installation. You can choose required packages.

By default, only the base packages are installed. However, we need the development packages. For that, Search for the “Devel” node and Click on the word “Default” next to it. Now “Default” becomes “Install”.

Shows the Screen after selecting Devel node

Figure 10: Shows the Screen after selecting Devel node.

Now click next and let Cygwin install all the required packages.

After installation Cygwin prompt you to create Desktop icon. Select and finish it.

Now open Cygwin and type make -v. It will show “GNU Make 3.82.90” and some information , here 3.82.90 is the version I installed on my system accordingly you will see some different one.

Shows the Screen after typing make -v for checking whether we have successfully installed Cygwin or not.

Figure 11: Shows the Screen after typing make –v for checking whether we have successfully installed Cygwin or not.

In case you are installing MinGW you need not to follow step 5 just follow simple screen instructions to install it. But remember while installing do not provide directory location that contain spaces.

Project Development:

Create new android project using New ->Android Application Project.

Enter the required fields and create the project. For this article I have created project named “JavaNativeCall” with package name “com.javanativecall.startup” with activity as “MainActivity.java” and layout file with name “activity_main.xml”. (See snapshots).

Shows the steps to create Project. Enter the Project name package name along with target SDK and Minimum SDK version

Figure 12: Shows the steps to create Project. Enter the Project name package name along with target SDK and Minimum SDK version.

Shows the Screen for Defining first activity and Layout file

Figure 13: Shows the Screen for Defining first activity and Layout file.

Now create a folder name “jni” in the main application for storing your native files and make file.

Create a new file using New->File and named then as “Android.mk” file that contains following codes:

Listing 1: Android.mk code

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := nativelibrary
LOCAL_SRC_FILES := intermediate.cpp first.cpp
LOCAL_LDLIBS    := -llog

include $(BUILD_SHARED_LIBRARY)

In the above code LOCAL_MODULE refers to the name of library you need to use in java code. LOCAL_SRC_FILES refers to the native code files and one intermediate file that bind java code to C++/C Classes or Functions.

For more advanced information about jni you can refer website: http://java.sun.com/docs/books/jni/

5. As in step 4 we have mentioned intermediate.cpp and first.cpp we need to create it.

For this article I am developing an Android app that perform Arithmetic operations where we pass the values from Android Activity (MainActivity.java) to C++ Class CFirst defined in First.cpp file and call the method MathOpertions and C++ files after performing operations returns the integer result that are displayed using Toast .

Listing 2: MainActivity.java

First.cpp file
#include <stdio.h>
#include <string.h>
#include "First.h"
#include <android/log.h>


CFirst::CFirst(void)
{
}
CFirst::~CFirst(void)
{
}

int CFirst::MathOperations(int fvalue,int svalue,const char *operation)
{
	int val;
	
	__android_log_print(ANDROID_LOG_INFO, "tag here", "message here%s",operation);
	if(operation)
		if(strcmp(operation,"A")==0)
		{
			val=1;
		}
		else if(strcmp(operation,"S")==0)
		{
			val=2;
		}
		else if(strcmp(operation,"M")==0)
		{
			val=3;
		}
		else if(strcmp(operation,"D")==0)
		{
			val=4;
		}

		__android_log_print(ANDROID_LOG_INFO, "tag here", "message here%d",val);
	

	switch(val)
	{
		case 1: return (fvalue + svalue);
			break;
		
		case 2: return (fvalue - svalue);
			break;

		case 4: return (fvalue/svalue);
			break;

		case 3:return (fvalue * svalue);
			break;

		default: return 0;

	}
}

Intermediate.cpp
#include <stdio.h>
#include <jni.h>
#include "First.h"

CFirst obj_CFirst;

extern "C" jint Java_com_javanativecall_startup_MainActivity_MathOperations(JNIEnv* env,jobject thiz, jint fvalue,jint svalue,jstring operation)
{
	
	const char *char_operation = env->GetStringUTFChars(operation,0);
	int result=obj_CFirst.MathOperations(fvalue,svalue,char_operation);
	
	return result;

}

Now, In MainActivity.java we need to load the library file and use it like this:

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

	private native int MathOperations(int fvalue,int svalue,String operation);

Calling the method MathOperations

result = MathOperations(fvalue, svalue, "A");

Similarly, design your activity_main.xml file. (You can find complete code with this article).

Now open Cygwin or MinGW and use the cd command to go to the directory where your project. (see Figure 14)

Shows the Screen after compiling NDK project. It shows the output file libnativelibrary.so file is created.

Figure 14: Shows the Screen after compiling NDK project. It shows the output file libnativelibrary.so file is created.

Now the time comes to use the NDK package we downloaded earlier, you will find a ndk-build file inside that package we need to use it for creating .so library file to use within java code for that use the command that will invoke the NDK build tool. In my case it is “/cygdrive/g/androidNDK/android-ndk-r8d-windows/ android-ndk-r8d-windows/ndk-build” and press enter you will see message that .so file install.

Now go to eclipse and refresh you project , you will find an armeabi folder is created inside libs folder that contains you library.so file (in my case libnativelibrary.so).

Shows the Snapshot of project structure that you need to follow in order to create NDK app

Figure 15: Shows the Snapshot of project structure that you need to follow in order to create NDK app.

We have completed with all stuff, it’s time to run and test the project.

Now run the project you will get following out put.

When you run the app you will see the above image, asking for input.

Figure 16: When you run the app you will see the above image, asking for input.

I have entered 3 and 6 as input for first and second number for performing arithmetic operations.

Figure 17: I have entered 3 and 6 as input for first and second number for performing arithmetic operations.

Now after entering input I have pressed + button and a function named ArithematicAddition is called and internally this function used native code to perform addition and display result using Toast as 9.

Figure 18: Now after entering input I have pressed “+” button and a function named “ArithematicAddition” is called and internally this function used native code to perform addition and display result using Toast as 9.

After +, I have pressed - button and a function named ArithematicSubtraction is called and internally this function used native code to perform subtraction and display result using Toast as 3.

Figure 19: After “+”, I have pressed “-” button and a function named “ArithematicSubtraction” is called and internally this function used native code to perform subtraction and display result using Toast as 3.

After +, I have pressed / button and a function named ArithematicDivision is called and internally this function used native code to perform division and display result using Toast as 2.

Figure 20: After “-”, I have pressed “/” button and a function named “ArithematicDivision” is called and internally this function used native code to perform division and display result using Toast as 2.

After /, I have pressed * button and a function named ArithematicMultiplication is called and internally this function used native code to perform multiplication and display result using Toast as 18.

Figure 21: After “/”, I have pressed “*” button and a function named “ArithematicMultiplication” is called and internally this function used native code to perform multiplication and display result using Toast as 18.

Conclusion:

In this article we learn:

How to use Android Native Development Kit (NDK) to use for Native programming in Java. Advantages:

  • Using NDK we need not to create new applications for one we created earlier in C/C++.
  • We can use effectiveness of C/C++ along with java.
  • It provide a platform to develop Games as most of the developer using C/C++ for developing Games for android, by using NDK with cocodx-2d.

See you next time, hope you liked.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login