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!!!!

Tuesday, 23 May 2017

Executor Service in Java

Hello Guys!!! Hope You all are doing well. Today I am going to discuss ExecutorService in java Thread.

The java.util.concurrent.ExecutorService interface represents an asynchronous execution mechanism which is capable of executing tasks in the background. An ExecutorService is very similar to a thread pool.

A simple Java ExectorService example

ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
}
});
executorService.shutdown();
  • First an ExecutorService is created using the newFixedThreadPool() factory method. This creates a thread pool with 10 threads executing tasks.
  • Second, an anonymous implementation of the Runnable interface is passed to the execute() method. This causes the Runnable to be executed by one of the threads in the ExecutorService.
A thread delegating a task to an ExecutorService for asynchronous execution.

Once the thread has delegated the task to the ExecutorService, the thread continues its own execution independent of the execution of that task.
ExecutorService Implementations
ExecutorService is an interface, we need to its implementations in order to make any use of it. The ExecutorService has the following implementation in the java.util.concurrent package:

  • ThreadPoolExecutor
  • ScheduledThreadPoolExecutor
Creating an ExecutorService
We can use the Executors factory class to create ExecutorService instances . Below are a few examples:

  • ExecutorService executorSerAvice1 = Executors.newSingleThreadExecutor();
  • ExecutorService executorService2 = Executors.newFixedThreadPool(10);
  • ExecutorService executorService3 = Executors.newScheduledThreadPool(10);
ExecutorService Usage
There are a few different ways to delegate tasks for execution to an ExecutorService:

  • execute(Runnable)
  • submit(Runnable)
  • submit(Callable)
  • invokeAny(...)
  • invokeAll(...)
execute(Runnable) method takes:- a java.lang.Runnable object, and executes it asynchronously. There is no way of obtaining the result of the executed Runnable, if necessary.
submit(Runnable) method:- also takes a Runnable implementation, but returns a Future object. This Future object can be used to check if the Runnable as finished executing.
submit(Callable) method:- similar to the submit(Runnable) method except that its call() method can return a result. The Runnable.run() method cannot return a result.
The Callable's result can be obtained via the Future object returned by the submit(Callable) method.
invokeAny():- method takes a collection of Callable objects, or subinterfaces of Callable. This method does not return a Future, but returns the result of one of the Callable objects. We have no guarantee about which of the Callable's results we get. Just one of the ones that finish.
invokeAll():- method invokes all of the Callable objects you pass to it in the collection passed as parameter. The invokeAll() returns a list of Future objects via which you can obtain the results of the executions of each Callable.
Dowload Example code 
package com.sks.softsolution.example4;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorServiceExample {

    public static void main(String[] args) {

        //example 1
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        // here we are using execute(runnable) method 
        executorService.execute(new RunnableThread("execute: "));

        //Example 2
        Future future = null;
        try {
            Thread.sleep(1000);
            System.out.println(".............................................");
            //ExecutorService submit() example, returns a Future object
            future = executorService.submit(new RunnableThread("submit: "));
            try {
                //returns current status of work.
                System.out.println("future.IsDone "+future.isDone());
                //returns null if the task has finished correctly.
                System.out.println("future.get() "+future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(".............................................");

        //Example 3 
        //ExecutorService Callable example
        future = executorService.submit(new CallableThread());
        try {
            System.out.println("Callable: future.get() = " + future.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(".............................................");

        //Example 4
        //ExecutorService invokeAny() method example
        Set<Callable<String>> callables = new HashSet<Callable<String>>();
        callables.add(new Callable<String>() {
            public String call() throws Exception {
                return "Task 1";
            }
        });
        callables.add(new Callable<String>() {
            public String call() throws Exception {
                return "Task 2";
            }
        });
        callables.add(new Callable<String>() {
            public String call() throws Exception {
                return "Task 3";
            }
        });

        String result = null;
        try {
            result = executorService.invokeAny(callables);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("invokeAny: result = " + result);
        System.out.println(".............................................");

        // Example 5
        // ExecutorService invokeAll() method example
        List<Future<String>> futures;
        try {
            futures = executorService.invokeAll(callables);
            for (Future<String> future1 : futures) {
                System.out.println("invokeAll: future.get = " + future1.get());
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        //Shutdown executor to avoid memory leak
        executorService.shutdown();

    }

    // Runnable thread
    static class RunnableThread implements Runnable {
        String name = "Runnable:";

        RunnableThread(String methodName){
            name = methodName;
        }

        @Override
        public void run() {
            for (int cnt = 0; cnt < 5; cnt++) {
                System.out.println(name + cnt);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }


 // Callable thread
    static class CallableThread implements Callable<Integer> {
        @Override
        public Integer call() {
            int cnt = 0;
            for (; cnt < 5; cnt++) {
                System.out.println("call:" + cnt);
            }
            return cnt;
        }
    }
}
Please read inline comment for proper understanding of above code.
executorService.shutdown() 
When you are done using the ExecutorService you should shut it down, so the threads do not keep running.
As for example, if your application is started via a main() method and your main thread exits your application, the application will keep running if you have an active ExexutorService in your application. The active threads inside this ExecutorService prevents the JVM from shutting down.
To terminate the threads inside the ExecutorService you call its shutdown() method. The ExecutorService will not shut down immediately, but it will no longer accept new tasks, and once all threads have finished current tasks, the ExecutorService shuts down. All tasks submitted to the ExecutorService before shutdown() is called, are executed.
If you want to shut down the ExecutorService immediately, you can call the shutdownNow() method. This will attempt to stop all executing tasks right away, and skips all submitted but non-processed tasks. There are no guarantees given about the executing tasks. Perhaps they stop, perhaps the execute until the end. It is a best effort attempt.

Thanks
Saurabh
Happy Coding!!!
Give your comment.

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...