Sunday, 2 July 2017

Working with Native code, JNI and core Java from command line

Hello Guys!!! Hope You all are doing well.
Today I am going to discuss “How to work with Java, JNI and C/C++ libs from command line”.
Actually  when you compile and generate .so file for your native code (c/c++) via NDK and try to load this library in Java by calling System.loadLibrary() method, then you will encounter most famous exception UnsatisfiedLinkError . 
The same .so file (generated by NDK) work well in Android Application. 

This behavior shows that .so file generated by NDK is compatible for Android and normally it is not work well with Core Java code. That's why Today i am going to discuss step by step approach for working with Native code, JNI and core Java. 
Step 1 Create folder and necessary file
I am using Linux machine (Ubuntu) for my development, so I am going to create a jniAPP folder under u directory of my machine.  In that folder I will keep following file 
  • .java file (Java class)
  • .h file (JNI header file)
  • .c or .cpp file (Native code)
  • .class file(generated file for java class)
  • .so file (generated native shared library)
Step 2 Compile java class & generate JNI header file
Use javac command to compile java and javah to generate JNI header file. As for example 
/u/jniApp/$ javac HelloJNI.java
/u/jniApp/$ javah HelloJNI


Step 3 compile library
Here we compile native code (c/c++) and create one shared library (.so). This library is used by our Java Class. 
gcc  -I "$JAVA_HOME/include" -I "$JAVA_HOME/include/linux" hellojni.c -fPIC -shared -o libJniHello.so
you can provide full java path in place of $JAVA_HOME  like this  "/usr/lib/jvm/java-8-openjdk-amd64/include"
Brief detail of gcc option used above
  • -l  used to link other shared libraries for current compilation 
  •  -fPIC  is a gcc option for creating a  position-independent code shared library, so that the shared library can readily be loaded at (more or less) any address in memory.
  • -o is option to specify the output file name for the executable
for more detail use man gcc in your terminal. 
Step 4 Run Java class
Now everything is setup properly so you can run your compile java class by using java command.
java -Djava.library.path=/u/jniApp/ HelloJNI
Here we are setting our created shared library (.so) file path so that our java class load library smoothly and run properly. In our case we created our library in /u/jniApp/ folder.
If you don't want to give library(.so) path in java  command line like above, in that case you have to modify load library java code as below
  static {
    String libPath = null;
    try{
      String mPath = new File (".").getCanonicalPath()+"/";
       String langKey = "java.library.path" ;
       System.setProperty ( langKey, mPath ) ;

       libPath = System.getProperty("java.library.path");
       System.out.println("java.library.path=" + libPath);
    }catch(Exception e){
      e.printStackTrace();
    }
    System.load(libPath+"libjavahowto.so");
    //System.loadLibrary("javahowto");  
}  

HelloJNI.java

public class HelloJNI {
                static {
                                System.loadLibrary("JNIHello");
                }
                private native void sayHello();
                public static void main(String args[]) {
                                JNIHello jniHello = new JNIHello();
                                jniHello.sayHello();
                }
}
HelloJNI.h file genetated bt javah commmand
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JNIHello */

#ifndef _Included_JNIHello
#define _Included_JNIHello
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     JNIHello
 * Method:    sayHello
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_JNIHello_sayHello
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif
hellojni.c
#include <jni.h>
#include <stdio.h>
#include "JNIHello.h"
/*
 * Class:     JNIHello
 * Method:    sayHello
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_JNIHello_sayHello
  (JNIEnv *env, jobject obj) {
        printf("Hello world!\n");
        return;
}
you can download whole project from above download link.

Tuesday, 30 May 2017

Build Gradle Android App from the Command Line

Hello Guys!!! Hope You all are doing well.
Today I am going to discuss “How to build android app from command line”.

You people can ask this question what is the need?
We have Android Studio IDE , Eclipse. Yaa Guys!!! your question is right .
Let me explain :-
  • As you guys know that Android Studio IDE internally used Gradle build System and Eclipse use ANT build System.
  • As a Android App developer we focus on our App business logic and ui, less bother for build system internally used by IDE.
  • But sometime for large android app(containing several module, lib, platform dependency), It is better to use command line for building the app(whole Eco system).
  •   Second thing, It is better to use command line  for your day to day development work, It will give you better understanding and power as a Developer.
Here I am going to discuss Android Gradle build via command line. I will discuss android ANT based build System(Eclipse) later . In Gradle system, We have two option to build android app.
  1. Build with Gradle (install Gradle and environment path) 
  2. Build with Gradle Wrapper (no need to install, created by Android Studio project)
Building with gradle wrapper (option 2) is easy. There is no need to install gradle build in your machine.  Just you have to go in your project directory (created by Android Studio ) and have to run some build command with gradlew .   
In window machine
gradlew task-name
in Mac/Linux
./gradlew task-name
you can see a list of all available build tasks for your project 
gradlew tasks
By running above command you find a list of task that you can run using gradlew for building your app. I am summarizing few of them in below table 
Command
Description
./gradlew build
build project, runs both the assemble and check task
./gradlew clean build
build project complete from scratch
./gradlew clean build
build project complete from scratch
./gradlew test
Run the tests
./gradlew connectedAndroidTest
Run the instrumesntation tests


Now Build with gradle (Option 1)
For building android app with gradle, we have  two option  Install gradle  or download gradle zip and use it. Gradle runs on all major platform (Linux, Mac window) and required only Java JDK or JRE version 7 or higher.  
Installing gradle on Linux(Ubuntu) , I will suggest use SDKMAN tools to install gradle on your machine.  After successfully installation on sdkman in your Linux machine run following command 
sdk install gradle 4.2.1
For more detail of gradle installation you can visit here.  Now open your terminal and run gradle,  output of this command is shown in below image 
Now in terminal go to your project (either created by Android Studio or  Eclipse, but make sure it contain build.gradle file)  root directory and run gradle tasks to see all available task you can perform by using gradle. 
Above image is showing gradle tasks command output for a empty project root directory. If you run this same command in a Android Studio project or an Android app project that contain build.gradle file you find a lot more option for building your project via gradle command. The most simple Android project has the following build.gradle file:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.3'
    }
}
apply plugin: 'com.android.application'
android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1" } 
gradle build command compiles, tests, and packages the code into an APK file. You can see results of the build process in the build folder.  For more detail on gradle build system you can visit Android Developer website. 

Thanks
Saurabh
Happy Coding!!!!

Thursday, 25 May 2017

Compile And Run a C/C++ Code In Linux(Ubuntu)

Hello Guys !!! Hope You all are doing well.
Toady I am going to discuss a simple topic for newbie in Linux(Ubuntu) .
How can compile and Run a C or C++ program on Linux operating systems using bash Terminal application?


To compile a C or C++ program on any Linux distro such as Ubuntu, Red Hat, Fedora, Debian and other Linux distro you need to install:

  1. GNU C and C++ compiler collection
  2. Development tools
  3. Development libraries
  4. IDE or text editor to write programs


Step #1: Install C/C++ compiler and related tools
If you are using Fedora, Red Hat, CentOS, or Scientific Linux, use the following yum command to install GNU c/c++ compiler:
# yum groupinstall 'Development Tools'

If you are using Debian or Ubuntu Linux, type the following apt-get command to install GNU c/c++ compiler:
$ sudo apt-get update
$ sudo apt-get install build-essential manpages-dev


Step #2: Verify installation
Type the following command to display the version number and location of the compiler on Linux:
  • $ whereis gcc
  • $ which gcc
  • $ gcc --version
Step #3: Compile the Program
Create a file called HelloInC.c using a text editor such as vi, emacs or joe or gedit as per your choice
/* Hello World in C Program */
#include<stdio.h>
main()
{
printf("Hello World in C!\n");
}
Use any one of the following syntax to compile the program called HelloInC.c:
cc program-source-code.c -o executable-file-name
OR
gcc program-source-code.c -o executable-file-name
OR
## assuming that executable-file-name.c exists ##
make executable-file-name
In this example, compile HelloInC.c, enter:
cc HelloInC.c -o demo
OR
gcc HelloInC.c -o HelloInC
OR
## assuming HelloInC.c exists in the current directory ##
make HelloInC
If there is no error in your code or C program then the compiler will successfully create an executable file called HelloInC in the current directory, otherwise you need fix the code.

Step #4 : Run or execute the program

Simply type the the program name:
$ ./ HelloInC
OR
$ /path/to/ HelloInC

Note:- Same way you can compile and run C++ programs. Just save your C++ file with extension .cpp and follow the same procedure. As for example
g++ HelloInCpp.cpp -o HelloInCpp
  • g++ is the invocation of the C++ component of GCC, the defacto compiler for C/C++ and whole host of other languages on the Linux platform. It's currently the only compiler capable of compiling the Linux kernel.
  • HelloInCpp.cpp is the c++ source file you wish to compile.
  • -o main specifies the name of the output file you wish to create once the source is compiled. The target source file and the target output file can be inverted if you wish, so
  • g++ -o HelloInCpp HelloInCpp.cpp is equally valid.
  • To then execute that program, you need to do ./ HelloInCpp in the terminal.

Some More Useful Tips for C/C++

How do I generate symbolic information for gdb and warning messages?
The syntax is as follows C compiler:
cc -g -Wall input.c -o executable

The syntax is as follows C++ compiler:
g++ -g -Wall input.C -o executable

How do I generate optimized code on a Linux machine?

The syntax is as follows C compiler:
cc -O input.c -o executable

The syntax is as follows C++ compiler:
g++ -O -Wall input.C -o executable

How do I compile a C program that uses math functions?
The syntax is as follows when need pass the -lm option with gcc to link with the math libraries:
cc myth1.c -o executable -lm

How do I compile a C++ program that uses Xlib graphics functions?
The syntax is as follows when need pass the -lX11 option with gcc to link with the Xlib libraries:
g++ fireworks.C -o executable -lX11

How do I compile a program with multiple source files?
The syntax is as follows if the source code is in several files (such as light.c, sky.c, fireworks.c):
cc light.c sky.c fireworks.c -o executable

C++ syntax is as follows if the source code is in several files:
g++ ac.C bc.C file3.C -o my-program-name

Thanks
Saurabh 
Happy Coding!!!!

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...