dcsimg

Writing “C” Code for Android

The Android SDK is strictly for Java Programmers -- however, the Native Development Kit cracks the door to let some "C" inside

Java Only, please

The supported and prescribed manner of creating Android applications is via the Android SDK and that means writing your applications in Java.

But what if you have a large body of code already written in C and you want to take leverage that investment for your Android efforts? Should you port your code to Java? Porting your code may be the right answer, but before you start refactoring your code into Java, you should have a look at the Android Native Development Kit (NDK).

Introduced around the release of Android version 1.5, the Android NDK permits developers to write code in “C” that is then callable from Android applications written in Java. The plumbing between the environments is known as the Java Native Interface, or JNI.

JNI has been around for years as a means to permit Java developers to access vendor SDKs or other available C code. Early on, the majority of software vendors’ SDKs were provided as C language static or dynamic libraries — however, this didn’t do Java programmers much good.

The solution to providing the functionality of those SDKs to Java applications was to write a “wrapper” dll in C. The wrapper implemented the Java Native Interface and then proxies calls to the third-party dll. Over time as Java became more popular, some thoughtful vendors began shipping their libraries Java-ready by providing their own JNI wrappers. Today Android developers can leverage C code with JNI with the help of the NDK.

Using the NDK

The Android NDK is a separate download from the Android development site. The NDK is supported on Linux, Mac OSX and Windows, however Windows users need to install Cygwin in order to run the tools properly.

After downloading the NDK, you need to run a script found in the build subdirectory named host-setup.sh. Before running the script you need to set the environment variable named ANDROID_NDK_ROOT to point to your installation of the NDK. For example, on my machine I perform this with:

export ANDROID_NDK_ROOT=~/Software/android/ndkpath

Running this script does basically two things:

It first verifies that your build tools are compatible and that your paths are properly setup for the C and C++ compilers, and the linker. It also locates the pre-built libraries shipped with the NDK which are specific to the Android environment.

./host-setup.sh

Detecting host toolchain.

CC         : compiler check ok (gcc)
LD         : linker check ok (gcc)
CXX        : C++ compiler check ok (g++)
Generate   : out/host/config.mk
Toolchain  : Checking for arm-eabi-4.2.1 prebuilt binaries

Host setup complete. Please read docs/OVERVIEW.TXT if you don't know what to do.

The script also writes out a file named config.mk into a directory named $ANDROID_NDK_ROOT/build/out/host. This file is used by the build tools.

# This file was autogenerated by host-setup.sh. Do not edit !
HOST_OS       := darwin
HOST_ARCH     := x86
HOST_TAG      := darwin-x86
HOST_CC       := gcc
HOST_CFLAGS   :=
HOST_CXX      := g++
HOST_CXXFLAGS :=
HOST_LD       := gcc
HOST_LDFLAGS  :=
HOST_AR       := ar
HOST_ARFLAGS  := 

Without this file, you cannot build NDK applications. Note that when running the script on my machine, I had to tweak the output directory location for the config.mk file to be written as there was an error in host-setup.sh. I was testing with version 1.5 of the NDK, so it is likely fixed in the latest release (1.6).

The NDK ships with two sample applications to exercise the NDK: a simple “Hello World” application named hello-jni and another project which demonstrates the use of both a static and a dynamic library. In addition to the “C” language components of these projects, the NDK also ships with sample Android Java applications to demonstrate loading and invoking the JNI code.

The NDK has a somewhat sophisticated build environment with a series of make files and make file “snippets” throughout the NDK installation. According to the documentation of the NDK, this build environment is very similar to the core Android source code base.

After getting the hello-jni code to compile, build and run successfully, I thought it would be worth the exercise to build one from scratch — or at least a healthy “cut, paste and modify” version of my own. So I created a simple application and JNI library to perform two basic tasks, each implemented as functions in a C source file. The first function just returns a string and the second increments a passed-in integer, returning the new value as an integer. Of course using JNI for such a task is not worth the effort, but once this is working, more sophisticated tasks are within our reach. Let’s have a quick look.

Building a JNI app

We’ll start by building our JNI C code, implementing the two methods of interest. Here is the C code.

#include <string.h>
#include <jni.h>

jstring
Java_com_msi_linuxmagazine_jnisample_LMJNI_stringFromJNI( JNIEnv* env,
                                                  jobject thiz )
{
    return (*env)->NewStringUTF(env, "Hello from Linux Magazine!");
}

jint
Java_com_msi_linuxmagazine_jnisample_LMJNI_incrementFromJNI(JNIEnv* env,jobject thiz,jint innumber)
{
	return innumber + 1;
}

Note the funny-looking function names! The methods are named according to the following pattern:

Java_<the fully qualified Java name space with “.” replaced with “_”>_methodname

In our Java code shown below, the Java package name is com.msi.linuxmagazine.jnisample and the class name is LMJNI. Therefore the function prefix is: “Java_com_msi_linuxmagazine_jnisample_LMJNI_”

Once the code is written, we also need a couple of Makefile snippets to grease the skids in the build process. The first file named Android.mk is required to compile the C code.


LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := linuxmagazine
LOCAL_SRC_FILES := linuxmagazine.c

include $(BUILD_SHARED_LIBRARY)

The Java application is stored beneath the ANDROID_NDK_ROOT in a directory named apps. This directory contains a file named Application.mk which tells the NDK where to save the created JNI library file: liblinuxmagazine.so. The Android code is in a sub-directory named project. Here is the contents of the Application.mk file:

APP_PROJECT_PATH := $(call my-dir)/project
APP_MODULES      := linuxmagazine

To build the JNI code, change directory to the base of your NDK installation and run make, along with the specific target we want the build system to compile:

cd $ANDROID_NDK_ROOT
make APP=linuxmagaine V=1

The V=1 makes the output verbose.

To perform a rebuild, add a -B option to the command line above. Here is what the verbose output looks like:

Android NDK: Building for application 'linuxmagazine'
Compile thumb  : linuxmagazine <= sources/samples/linuxmagazine/linuxmagazine.c
build/prebuilt/darwin-x86/arm-eabi-4.2.1/bin/arm-eabi-gcc -Ibuild/platforms/android-1.5/arch-arm/usr/include -march=armv5te -mtune=xscale -msoft-float -fpic -mthumb-interwork -ffunction-sections -funwind-tables -fstack-protector -fno-short-enums -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_5E__ -D__ARM_ARCH_5TE__   -Isources/samples/linuxmagazine -DANDROID  -O2 -DNDEBUG -g    -c -MMD -MP -MF out/apps/linuxmagazine/android-1.5-arm/objs/linuxmagazine/linuxmagazine.o.d.tmp sources/samples/linuxmagazine/linuxmagazine.c -o out/apps/linuxmagazine/android-1.5-arm/objs/linuxmagazine/linuxmagazine.o
build/core/mkdeps.sh out/apps/linuxmagazine/android-1.5-arm/objs/linuxmagazine/linuxmagazine.o out/apps/linuxmagazine/android-1.5-arm/objs/linuxmagazine/linuxmagazine.o.d.tmp out/apps/linuxmagazine/android-1.5-arm/objs/linuxmagazine/linuxmagazine.o.d
SharedLibrary  : liblinuxmagazine.so
build/prebuilt/darwin-x86/arm-eabi-4.2.1/bin/arm-eabi-gcc -nostdlib -Wl,-soname,liblinuxmagazine.so -Wl,-shared,-Bsymbolic  out/apps/linuxmagazine/android-1.5-arm/objs/linuxmagazine/linuxmagazine.o -Wl,--whole-archive  -Wl,--no-whole-archive   build/platforms/android-1.5/arch-arm/usr/lib/libc.so build/platforms/android-1.5/arch-arm/usr/lib/libstdc++.so build/platforms/android-1.5/arch-arm/usr/lib/libm.so   -Wl,--no-undefined   -Wl,-rpath-link=build/platforms/android-1.5/arch-arm/usr/lib /Users/fableson/Software/android/android-ndk-1.5_r1/build/prebuilt/darwin-x86/arm-eabi-4.2.1/bin/../lib/gcc/arm-eabi/4.2.1/interwork/libgcc.a -o out/apps/linuxmagazine/android-1.5-arm/liblinuxmagazine.so
Install        : liblinuxmagazine.so => apps/linuxmagazine/project/libs/armeabi
mkdir -p apps/linuxmagazine/project/libs/armeabi
install -p out/apps/linuxmagazine/android-1.5-arm/liblinuxmagazine.so apps/linuxmagazine/project/libs/armeabi/liblinuxmagazine.so
build/prebuilt/darwin-x86/arm-eabi-4.2.1/bin/arm-eabi-strip --strip-debug  apps/linuxmagazine/project/libs/armeabi/liblinuxmagazine.so

That was fun — now we have our liblinuxmagazine.so sitting in $ANDROID_NDK_ROOT/apps/linuxmagazine/libs/armeabi.

Now let’s create our Android Java application to exercise our JNI code.

The application has two TextView (edit box) fields and two buttons, organized into pairs. The first pair is used to exercise the “get a string” JNI function and the second is used for the “increment a number” function. This image shows the user interface of the application before the buttons are clicked.

Before running JNI code
Before running JNI code

Now, let’s look at the code for this Java application:

package com.msi.linuxmagazine.jnisample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;

public class LMJNI extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btnGetString = (Button) this.findViewById(R.id.btnGetString);
        btnGetString.setOnClickListener(new Button.OnClickListener() {
        	public void onClick(View v) {
	                TextView label = (TextView) findViewById(R.id.TheLabel);
	                label.setText(stringFromJNI());   // calling a JNI function here!
        	}
        });

        Button btnAddNumber = (Button) this.findViewById(R.id.btnAddNumber);
        btnAddNumber.setOnClickListener(new Button.OnClickListener(){
        	public void onClick(View v) {
	                TextView numberField = (TextView) findViewById(R.id.number);
	                int operand = Integer.parseInt(numberField.getText().toString());
	                int answer = incrementFromJNI(operand);  // calling a JNI function here!
	                numberField.setText("" + answer);
        	}
        });
    }

    // declare the externally provided methods
    public native String  stringFromJNI();
    public native int incrementFromJNI(int number);

    static {
    	// load our JNI library.  Note, leave off the "lib" and the ".so"
        System.loadLibrary("linuxmagazine");
    }
}

And here is the layout for the user interface:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/TheLabel" android:text="LMJNI ..."/>

<Button android:text="Get String" android:id="@+id/btnGetString" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/number" android:text="10" android:numeric="integer"/>

<Button android:text="Add Number" android:id="@+id/btnAddNumber" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

</LinearLayout>

Some things to note in this code snippet:

  • We are using a basic single-Activity Android application with a simple user interface layout: two pairs of TextView and Button.
  • A call to System.loadLibrary loads our JNI shared library.
  • We define each of the implemented methods. Note the native qualifier on the methods.
  • Each user interface element has an “id” attribute so we can get access to it at run-time, a standard Android practice.
  • We create onClick handlers for each button and within those methods, we invoke the native code. These click handlers have no idea that the code is external to the application.
  • If the native methods were missing, the application would throw an exception. The app really should have a try/catch block.

The JNI library is automatically deployed as part of our apk file and the code runs as expected at runtime!

After selecting the buttons we see the string has been returned from the JNI code and the number 10 has been incremented to 11.

After running JNI code
After running JNI code

This is just scratching the surface of using the NDK, but hopefully sheds some light on using C with the Android platform. There is a subset of the system libraries shipped with the NDK — the documentation warns against using other libraries as the underlying architecture is at risk of changing. I personally would not be too concerned with this as the entire mobile space is rapidly changing!

This code was compiled against version 1.5 of the NDK and was found to run just fine against the 1.5 and 2.1 Android emulators.

Comments on "Writing “C” Code for Android"

You claim that males use these thoughts video games to gain belief in girls, but that just exhibits a complete lack of information on the concept of trust.

Just beneath, are many totally not related internet sites to ours, however, they are surely worth going over.

Hey there would you mind letting me know which webhost you’re using? I’ve loaded your blog in 3 completely different browsers and I must say this blog loads a lot quicker then most. Can you recommend a good web hosting provider at a fair price? Cheers, I appreciate it!

A single thing that actually, definitely assisted was actually a portable percussive massager that our team had.

Here is an excellent Weblog You may Obtain Intriguing that we encourage you to visit.

That could be the end of this write-up. Here you?ll obtain some web-sites that we feel you?ll value, just click the hyperlinks.

Very handful of websites that take place to become comprehensive beneath, from our point of view are undoubtedly effectively worth checking out.

Here is an excellent Blog You might Discover Interesting that we encourage you to visit.

Massage therapy eases many of the usual distress while pregnant, including backaches, a stiff back, lower leg aches, frustrations, edema, and painful, swollen ankles and shoes.

And the major factor of a site is the building of the internet site while shopping from a shop you want to see each type of item of various cost so the e-commerce site should give ideal and also easy purchasing experience.

We came across a cool internet site which you may well appreciate. Take a appear for those who want.

Washington DC is the excellent place to quit midway on your eastern coast journey Not just is budget plan pleasant due to the fact that every one of the monuments are free, however the city has one of the very best walking experiences you’ll have in the whole nation.

Doctors simply let that go over their heads, because I was on depression meds for a motive, in order that couldn’t have anything to do with it. So they lower me 30mg a day and added 100mg of pristiq.

Below you?ll find the link to some web pages that we consider you need to visit.

Soup and Vegetables (no Fruit) – Eat a number of cooked, raw contemporary greens or canned greens all through the day.

I am really happy to glance at this blog posts which contains plenty of helpful information, thanks for providing these data.

five hundredextended familyIntwo twonuclear familyrevolting disgustingorderextended familytwo to help twonuclear familyrevolting disgustingarevolting disgustingfive hundred five hundredextended familyprospectiveextended family five hundredbusiness proprietorfive hundred properly five hundredextended familyhandleextended familytwofive hundred theirrevolting disgustingtwofive hundred vendor/broker and even five hundredtwonuclear familymakerevolting disgustingextended family the choice twoasrevolting disgustingtwo twotorevolting disgusting five hundredtwonuclear familyrevolting disgustingwhatnuclear familytwofive hundred five hundredfurnishingsextended family five hundredtwonuclear familyrevolting disgustingtheyrevolting disgustingfive hundred five hundredpurchasefive hundred five hundredtwonuclear familyrevolting disgustingdirectextended familytwofive hundred five hundredextended familyrevolting disgustingfromrevolting disgustingtwofive hundred a large five hundredfield five hundredextended familyretailrevolting disgustingtwo five hundredtworevolting disgustingandextended family which ones nuclear familyrevolting disgustingtheyrevolting disgustingtwo five hundredimposerevolting disgustingtwofive hundred twonuclear familyrevolting disgustingonrevolting disgustingextended familyfive hundred twoextended familyrevolting disgustingarevolting disgustingextended familyfive hundred supplier, five hundredtworevolting disgustingwefive hundred twolaboredtwofive hundred five hundredrevolting disgustingwithrevolting disgustingfive hundred twonuclear familyTomnuclear familyfive hundred five hundredLoughneynuclear familytwo extended familyofnuclear familytwofive hundred five hundredrevolting disgustingCubiclerevolting disgustingnuclear family five hundrednuclear familyrevolting disgustingDepotrevolting disgustingnuclear familytwofive hundred twotorevolting disgustingfive hundred five hundrednuclear familycreatedrevolting disgustingextended family a good, better, greatest situation andrevolting disgustingfive hundred extended familyrevolting disgustingcreatedrevolting disgustingnuclear family five hundredtwoextended familybudgetsrevolting disgustingnuclear familytwo twonuclear familyaroundextended familytwo twoanuclear familytwofive hundred twoextended familyfictitiousnuclear familyfive hundred workplace space that’s five hundredtwonuclear familyapproximatelyextended family five hundredrevolting disgusting2revolting disgustingnuclear familytwofive hundred,twoextended family000revolting disgustingextended family sq. feet.

The waste conversion approach avoids these emissions by capturing the gas and turning it into a item.

Our parks are outfitted with a variety of thrilling facilities that will certainly have you and your family beaming from the beginning.

I like the helpful information you provide in your articles. I’ll bookmark your weblog and check once more right here regularly. I am rather certain I’ll be told many new stuff proper here! Best of luck for the following!

Wonderful story, reckoned we could combine a handful of unrelated data, nonetheless genuinely worth taking a look, whoa did a single master about Mid East has got much more problerms also.

Although web sites we backlink to beneath are considerably not related to ours, we feel they are truly worth a go as a result of, so have a look.

Just beneath, are various totally not connected web-sites to ours, having said that, they’re certainly worth going over.

Awesome article.

We came across a cool web-site that you just may possibly appreciate. Take a search should you want.

If you would like to increase your familiarity simply keep visiting this website and be updated with the most up-to-date information posted here.

Just beneath, are many absolutely not connected web sites to ours, however, they’re certainly really worth going over.

The details talked about in the post are a number of the ideal accessible.

I do agree with all of the ideas you have introduced for your post. They are very convincing and can definitely work. Still, the posts are very brief for beginners. May you please lengthen them a bit from subsequent time? Thanks for the post.

Their theories drew heavily from the work of earlier philosophers and highlighted existential nervousness as an necessary component of mental well being.

It has to be constructed well to get more space where you can store your items. There are several ways you can make sure that your home is at limited risk when it comes to flood damage. The one area you will only want to keep an eye on is with oxidation.

We came across a cool web page that you may possibly love. Take a search for those who want.

Respect to author, some wonderful selective information.

Here is a superb Weblog You may Find Intriguing that we encourage you to visit.

The mayor of St. Tropez banned topless females and ordered law enforcement to hover the beaches in helicopters.

Although internet sites we backlink to beneath are considerably not connected to ours, we really feel they’re truly worth a go by way of, so have a look.

We like to honor numerous other world-wide-web web pages on the internet, even if they aren?t linked to us, by linking to them. Under are some webpages really worth checking out.

What’s Taking place i am new to this, I stumbled upon this I’ve found It absolutely useful and it has aided me out loads. I’m hoping to contribute & assist other customers like its aided me. Great job.

Although internet websites we backlink to below are considerably not related to ours, we really feel they are essentially worth a go through, so have a look.

Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

If sometime you get married, preserve these in mind, and your wife shall be a content and joyful girl.

That would be the end of this report. Right here you will discover some web-sites that we feel you will appreciate, just click the hyperlinks.

I’m nearing my one year mark and I actually have found that I am capable of eat sweets and snacks often. I do watch what I eat but I’ve always completed that-even once I wasn’t the fitting shape and measurement. So glad you shared!

Very few internet websites that happen to be detailed below, from our point of view are undoubtedly properly really worth checking out.

Access the perfect success, personal development, health, fitness, business, and monetary advice….all for FREE!

Thanks to my father who shared with me regarding this weblog, this web site is genuinely remarkable.

We came across a cool web page that you just might get pleasure from. Take a appear when you want.

Everything is very open with a very clear description of the issues. It was definitely informative. Your website is very useful. Thanks for sharing!

Good day! Do you know if they make any plugins to assist with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains. If you know of any please share. Many thanks!

Very couple of web-sites that happen to be detailed below, from our point of view are undoubtedly nicely really worth checking out.

Leave a Reply