Skip to main content

Overview of how to develop native code with Android NDK:

 
  1. Create a jni directory and place native source code under $PROJECT/jni/...
  2. Create Android.mk directory and place it under $PROJECT/jni/... to describe source code to the NDK build system.
  3. Create Application.mk and place it under $PROJECT/jni/...to describe project in more details to the NDK build system.It is an optional.
  4. Finally need to build native source code by running '$NDK/ndk-build' from project directory or it's sub-directory.
Android.mk
An Android.mk file is a small build script that we write to describe sources to the NDK build system. It's syntax is like this...

LOCAL_PATH:=$(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE:=hello-jni
LOCAL_SRC_FILES:=hello-jni.c

include $(BUILD_SHARED_LIBRARY)

NDK groups your sources into "modules", where each module can be one of the following:
  • Static library
  • Shared library
We can write several module in a single 'Android.mk' or can write several 'Android.mk' for each module.
Application.mk(Optional)
An Application.mk file script that we write to describe project to the NDK build system.It's syntax is like this...

to support hardware FPU instructions on ARMv7 based devices
APP_ABI:=armeabi-v7a
to support the IA-32 instruction set
APP_ABI:=x86
to support the MIPS instruction set
APP_ABI:=mips
to support all at the same time

APP_ABI:=armeabi armeabi-v7a x86 mips or
APP_ABI:=all

This allows us to do following:
  • The exact list of modules required by the application.
  • The CPU architecture to generate machine code for.
  • Optional information, like whether you want a release or debug build, specific C or C++ compiler flags and others that should apply to all modules being built.
This file is optional: by default the NDK provide one that simply builds all the modules listed from the Android.mk (and all the makefiles it includes) and target the default CPU ABI (armeabi).
NDK-BUILD
The 'ndk-build' script, located at the top of the NDK installation path can be invoked directly from your application project directory (i.e. the one where your AndroidManifest.xml is located) or any of its sub-directories. For example:
dilip@dilip-zenga:~/android-ndk-r9c/samples/hello-jni$ ~/Desktop/android-ndk-r9c/ndk-build

On success, this will copy the generated binary modules i.e. Shared library to the appropriate location in the project tree.

Example:

HelloJni.java

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


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

        /* Create a TextView and set its content.
         * the text is retrieved by calling a native
         * function.
         */
        TextView  tv = new TextView(this);
        tv.setText( stringFromJNI() );
        setContentView(tv);
    }

    /* A native method that is implemented by the
     * 'hello-jni' native library, which is packaged
     * with this application.
     */
    public native String  stringFromJNI();

    /* This is another native method declaration that is *not*
     * implemented by 'hello-jni'. This is simply to show that
     * you can declare as many native methods in your Java code
     * as you want, their implementation is searched in the
     * currently loaded native libraries only the first time
     * you call them.
     *
     * Trying to call this function will result in a
     * java.lang.UnsatisfiedLinkError exception !
     */
    public native String  unimplementedStringFromJNI();

    /* this is used to load the 'hello-jni' library on application
     * startup. The library has already been unpacked into
     * /data/data/com.example.hellojni/lib/libhello-jni.so at
     * installation time by the package manager.
     */
    static {
        System.loadLibrary("hello-jni");
    }
}

hello-jni.c

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

/* This is a trivial JNI example where we use a native method
 * to return a new VM String. See the corresponding Java source
 * file located at:
 *
 *   apps/samples/hello-jni/project/src/com/example/hellojni/HelloJni.java
 */
jstring
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
                                                  jobject thiz )
{
#if defined(__arm__)
  #if defined(__ARM_ARCH_7A__)
    #if defined(__ARM_NEON__)
      #define ABI "armeabi-v7a/NEON"
    #else
      #define ABI "armeabi-v7a"
    #endif
  #else
   #define ABI "armeabi"
  #endif
#elif defined(__i386__)
   #define ABI "x86"
#elif defined(__mips__)
   #define ABI "mips"
#else
   #define ABI "unknown"
#endif

    return (*env)->NewStringUTF(env, "Hello from JNI !  Compiled with ABI " ABI ".");
}

Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := hello-jni
LOCAL_SRC_FILES := hello-jni.c

include $(BUILD_SHARED_LIBRARY)


Application.mk

APP_ABI:=all

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.hellojni"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="3" />
    <application android:label="@string/app_name"
                 android:debuggable="true">
        <activity android:name=".HelloJni"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


Previous       Next      

Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. I really liked the blog. It is quite user-friendly and intuitive for the users. I personally believe blogs like this depict the importance of React slack clone and other clone apps. Clone apps are of great importance help businesses to revamp their business by bringing them to the digital world. CLone apps like Instacart clone app, Netflix clone, and several others are delineated with the same features making them the best amongst all. Thanks for sharing this information.

    ReplyDelete
  3. such a great blog! thank you keep sharing ! I also recommend Amritsar Digital Academy who provides digital marketing course so that you can promote your business and can earn passive amount of money.

    ReplyDelete

Post a Comment

Popular posts from this blog

Android O New Features Overview

This post assumes, you are an experienced developer who wants to get started with the latest version of Android. Android O is not a huge update to the OS and application framework like M but it still has many useful features for both developer and an user. Android O has focus on below areas. Notification redesigned Picture-in-Picture(PIP)  Visual adaption for different devices  Battery life improved Setting app reorganized Notification redesigned: Android O notification changes includes more easy and manageable way to manager your notification behavior and settings. It includes: Notification Channel: Notification channel allows you to create user customizable channel for each type of notification you wanna display. A single application can have multiple channel, a separate channel for each type of notification you wanna display. Having said this, you can create s separate channel for audio & image notification. User can disable specific notification channel instead

Java 8 Overview

Java 1.8 has introduced major features for the Java developers. It includes various upgrade to the Java programming, JVM, Tools and libraries. The main purpose of Java 1.8 release has been to simplify programming, utilize functional programming benefits and enable parallel programming/processing in Java programming language. Java 1.8 feature  Lambda(->) Expression Functional interfaces Default Methods in interface static method inside interface     Pre defined functional interfaces Predicate Function Consumer ::(Method reference and constructor reference by using double colon(::)operator) Stream API Date & Time API