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"

Here are some links to web sites that we link to because we think they are really worth visiting.

They guarantee the client with a tactically and also technically sound online search engine optimisation, as baseding on the requirements of the customer.

Some business owners in the past have made use of covert message, or message that coincides shade as the background, to deceive online search engine into indexing them differently.

The sooner you contact the locksmith professional the greater your chances are for resolving the problem.

We came across a cool site which you may get pleasure from. Take a search if you want.

Here is a good Blog You may Locate Fascinating that we encourage you to visit.

Check beneath, are some completely unrelated sites to ours, nonetheless, they may be most trustworthy sources that we use.

Wonderful story, reckoned we could combine a handful of unrelated data, nonetheless genuinely really worth taking a appear, whoa did one particular find out about Mid East has got much more problerms too.

Holiday plans (for this week actually, which I did not go for) and unreasonnable ideas after 48h (recommendations on how I could move my job to his country and work from there), sweet talker, recognized what I need in life.

Creating that” It’s not uncommon in today’s SEO landscape to wake up and also discover an abrupt decrease of natural search traffic and/or key phrase positions … By benefiting from the knowledge that is readily available for free, brand names with low budget plans can recuperate from Search Engine Optimization problems,” Marc Purtell suggests using Google Web designer Devices, Howling Frog, and also the BrowSEO Crawler Simulator to investigate and also assist correct ranking loss concerns.

Obstructing the robots with this Meta Tag implies the site will never ever appear on a search results page page; it’s an SEO deadly.

Every when inside a while we select blogs that we study. Listed beneath would be the newest web-sites that we opt for.

I’ve learn several excellent stuff here. Definitely value bookmarking for revisiting. I surprise how a lot attempt you put to make any such great informative website.

The best time to purchase Mitsubishi air conditioners is in late August when it is the end of the season. There are many online sites that help to guide you in renovating and remodeling your home. That’s why stylish furniture would be good here too.

The time to read or visit the content material or websites we have linked to below.

Keep in mind that your site is not the just one that undertakes optimization, and that there is completely only one position for each of the Top 50 ranking for every online search engine.

The phrase ‘seo’ ought to not confuse any person, although it might appear peculiar till a little is learnt about it. Some details and also some ideas, it is anticipated, suffices to get rid of the confusion that generally covers the mind of the beginner.

I used to be suggested this blog by way of my cousin. I am now not positive whether or not this post is written by way of him as no one else understand such unique approximately my problem. You are amazing! Thank you!

One of our visitors just lately proposed the following website.

The net has actually become an excellent market place and to advance the business online; you will certainly need the right devices to entice potential consumers and grow your business.

Hi there! This is kind of off topic but I need some help from an established blog. Is it difficult to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about making my own but I’m not sure where to begin. Do you have any tips or suggestions? Thank you

Both organic and environmental factors have an effect on the occurrence of hysteria issues.

This electronic pulse massager is perhaps the most helpful anxiety relaxation cellphone on the market.

Convert kilograms to pounds by multiplying by two.205, and pounds to kgs by multiplying by .454.

Utilizing organized data markup in your website you will certainly be supplying maximum information to the search engines as well as the site visitors will certainly get the required details from the online search engine.

Lambert credited a portion-controlled food plan and circuit-coaching exercises for her weight loss, Celebrity Health & Fitness reported.

A perfect ecommerce package deal is capable of managing all the needs of the client as well as consists of giving customized e-solutions to the customer’s discriminating company needs.

To fix a split engine block with a stitch, a stitch has to be positioned in the crack making use of a hammer, drill bit or torque wrench.

five hundredtwoextended familyThenuclear familytwo requirements five hundredtwoextended familyforrevolting disgustingextended familytwo five hundredtwofurnishingrevolting disgustingtwofive hundred five hundrednuclear familythisextended familytwofive hundred workplace house twoextended familyarerevolting disgustingtwofive hundred five hundredtwonuclear familyrevolting disgustinganuclear family five hundrednuclear familyreceptionrevolting disgustingfive hundred area, five hundredextended familyrevolting disgustingarevolting disgustingnuclear familyfive hundred five hundredtwonuclear familyrevolting disgustingbreaktwofive hundred twonuclear familyroomrevolting disgustingextended family, arevolting disgustingextended familyfive hundred twoextended familyconventionextended familytwofive hundred tworevolting disgustingroomnuclear familytwofive hundred, five hundrednuclear familyarevolting disgustingnuclear familytwo five hundredmaster office, andrevolting disgusting a piece house five hundredtwoextended familyrevolting disgustingholdingnuclear familytwofive hundred as much as five hundredtwonuclear familyfournuclear family five hundrednuclear familycubiclesrevolting disgustingextended familyfive hundred.

Very couple of internet sites that occur to be in depth below, from our point of view are undoubtedly very well really worth checking out.

My partner and I absolutely love your blog and find many of your post’s to be exactly what I’m looking for. Does one offer guest writers to write content for you? I wouldn’t mind composing a post or elaborating on a lot of the subjects you write about here. Again, awesome blog!

Excellent article. I absolutely appreciate this site. Keep it up!

Every the moment inside a although we opt for blogs that we study. Listed below would be the most recent internet sites that we decide on.

Here are a few of the sites we suggest for our visitors.

Here are some of the sites we recommend for our visitors.

Please go to the internet sites we comply with, which includes this a single, as it represents our picks in the web.

If you already have an internet site, they need to do a complete checking of your current web site and assess its efficiency with regards to your rival’s site, so that they can get you the maximum advantage out of the Search Engine Optimization.

The information and facts mentioned inside the article are a number of the most beneficial readily available.

If storing, add a squeeze of lemon juice and store your drink in an hermetic glass container.

To fix a cracked engine block with a stitch, a stitch has to be positioned in the split utilizing a hammer, drill little bit or torque wrench.

Writing Blog sites can be enjoyable as well as if the writer comes to be a Google AdSense associate then they could make money from their blog posts also.

Always a big fan of linking to bloggers that I adore but do not get lots of link like from.

Firms and their internet developers kept trying to catch-up with the online search engine standard.

If, on the other hand, your website supplies a selection of products and services, your success price will probably be higher, which suggests you require less site visitors which, in turn, indicates your seo solutions needs will certainly be much less.

Have you ever thought about publishing an e-book or guest authoring on other blogs? I have a blog based upon on the same topics you discuss and would really like to have you share some stories/information. I know my subscribers would value your work. If you are even remotely interested, feel free to shoot me an e-mail.

Here are a number of the web pages we advocate for our visitors.

Compaq Drivers Download Utility claims to be suitable with all versions of Windows working techniques and no assist all major hardware manufacturers in their driver catalog.

Poverty is a motive why some men depart their happens as a result of a poor man can hardly ever be respected even when he’s proper or has variety phrases for his spouse.

Recap Tampa search engine optimization and web design Tampa services have made many on-line companies to prosper in the manner in which they run as their internet site always stick out which brings in much more visitors to the web site which in turn suggests a great deal of clients to the business.

Here is an excellent Blog You may Uncover Intriguing that we encourage you to visit.

Leave a Reply