O'Reilly logo

Programming Android by Zigurd Mednieks, G. Blake Meike, Masumi Nakamura, Laird Dornin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Building Your Own Custom Library Modules

This section puts together several techniques shown throughout the chapter to create and use a simple C module that uses the math library to calculate a power. We’ll start with the Android.mk file. Notice that we need to build the library (sample_lib) and export the includes. This library is then referenced in the sample:

LOCAL_PATH := $(call my-dir)

  # this is our sample library
include $(CLEAR_VARS)

LOCAL_MODULE    := sample_lib
LOCAL_SRC_FILES := samplelib/sample_lib.c
  # we need to make sure everything knows where everything is
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/samplelib

include $(BUILD_STATIC_LIBRARY)

  # sample uses the sample lib we created
include $(CLEAR_VARS)

LOCAL_MODULE    := sample
LOCAL_SRC_FILES := sample.c
LOCAL_LDLIBS    := -llog
  # We load our sample lib 
LOCAL_STATIC_LIBRARIES := sample_lib

include $(BUILD_SHARED_LIBRARY)

We have a short header file, sample_lib.h:

#ifndef SAMPLE_LIB_H
#define SAMPLE_LIB_H

extern double calculatePower(double  x, double  y);

#endif

The source code for our function, sample_lib.c, is:

#include "sample_lib.h"
  // we include the math lib
#include "math.h"

  // we use the math lib
double calculatePower(double  x, double  y) {
    return pow(x, y);
}

Following is the sample.c file that glues our sample_lib library to the Java code:

 // we include the sample_lib #include "sample_lib.h" #include <jni.h> #include <android/log.h> #define LOGINFO(x...) __android_log_print(ANDROID_LOG_INFO,"SampleJNI",x) jdouble Java_com_oreilly_demo_pa_ch18_SampleActivityWithNativeMethods_calculatePower( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required