Sunday, December 27, 2015

.aar (Android Archive Library) Format Android

Purpose of AAR

Android AAR files build upon this concept to allow you to package not only the source code but also the libraries self contained Android resources. The library can have its own manifest and resources and can also optionally provide assets, NDK built libraries, proguard configuration and even its own custom lint filters.  This is all bundled into a zip archive that can be published to a repository for your team (or the world!) to get easy access from a Gradle build.
  1. The 'aar' bundle is the binary distribution of an Android Library Project.
  2. The file extension is .aar, and the maven artifact type should be aar as well, but the file itself a simple zip file with the following entries:
  • /AndroidManifest.xml (mandatory)
  • /classes.jar (mandatory)
  • /res/ (mandatory)
  • /R.txt (mandatory)
  • /assets/ (optional)
  • /libs/*.jar (optional)
  • /jni/<abi>/*.so (optional)
  • /proguard.txt (optional)
  • /lint.jar (optional)
These entries are directly at the root of the zip file.


Creating an AAR library project

The good news is creating an AAR library is easy and Android Studio will do all the hard work for you.




  1. Start by selecting New Module… from the File menu
  2. Select Android Library as the module to be created (see Figure )
  3. Step through the process of using a template for the creation of your library much like creating a new project

One key difference in the created library and an Android application will be the libraries Gradle build script includes apply plugin: ‘com.android.library’ instead of apply plugin: ‘com.android.application’.

When you build your project the AAR file will automatically be assembled and placed in these folders.

| build
| outputs
      | aar
           | applib-debug.aar
           | applib-release.aar


Using AAR

You have a few choices as to how to include your AAR library in your project:

  • Publish to a external Maven repository
  • Publish to a local repository
  • Access from a local folder

While Gradle can be used to directly publish to repositories such as Maven Central, this article doesn’t cover publishing your AAR file to Maven repositories.

To include your AAR library as a dependency from a local folder:
  1.  Copy the AAR file into the libs folder in your project. Create this folder if it doesn’t exist. It needs to be located in the same folder as your application Gradle build file, not the top level project folder.
  2. Declare the libs folder as a dependency repository in your application Gradle script.

repositories {
    flatDir {
        dirs: 'libs'
    }
}

dependencies {
   compile 'com.kevinpelgrims.library:library:1.0.0@aar'
}

The Gradle flatDir repository declaration allows you to declare a file system directory that is a repository for dependencies for the project. In the example above I am using the libs folder which needs to be located relative to the location of the build script. The name of this folder does not have to be libs and it is also possible to declare multiple fileDir folders in the one project.


    3. Declare your AAR library as a dependency:

dependencies {
    compile(name:'yourlibraryname', ext:'aar')
}

AARs vs Jars:

The main difference between a Jar and a AAR is that AARs include resources such as layouts, drawables etc. This makes it a lot easier to create self-contained visual components. For example if you have multiple apps that use the same login screen, with Jars you could share classes but not the layout, styles, etc., you still had to duplicate them. With AARs everything is bundled in one neat package.

Advantages of AAR:

  • Allow you to package not only the source code but also the libraries self contained Android resources.
  • Allow easily distribute and use aar archive file.
  • Allow to reuse the code as well as resources.


Reference Link:
http://tools.android.com/tech-docs/new-build-system/aar-format
https://androidbycode.wordpress.com/2015/02/23/building-an-aar-library-in-android-studio/
http://kevinpelgrims.com/blog/2014/05/18/reference-a-local-aar-in-your-android-project/


Saturday, December 26, 2015

Gradle Android Studio

Introduction:

  1. Gradle is an automated build toolkit that can integrate into lots of different environments, via plugins.
  2. Minimize Configuration Required for New Projects: Gradle has a set of default configuration settings that are automatically applied to every project you create in Android Studio. If you're developing a project that doesn't adhere to these default configuration rules, Gradle is easy to customize.
  3. Declare Project Dependencies: Dependencies can be modules, JAR files or libraries, and they can be located either on the local file system or a remote server.
  4. Test Your Project: Gradle automatically generates a test directory and a test APK from your project's test sources and can run your tests during the build process.
  5. Generate Signed APKs: If you add all the necessary information, such as keyPassword and keyAlias, to your Gradle build file, you can use Gradle to generate signed APKs. 
  6. Generate Multiple APKs from a Single Module: Gradle can generate multiple APKs with different package and build configurations from a single module. This feature is particularly handy for Android developers, for several reasons:
    Support a Wide Range of Devices,
    Offer Different Versions of an App like Demo or Pro

Gradle Build Files:

  1. Gradle build files use a Domain Specific Language or DSL to define custom build logic and to interact with the Android-specific elements of the Android plugin for Gradle.
  2. Android Studio projects consist of one or more modules, which are components that you can build, test, and debug independently. Each module has its own build file, so every Android Studio project contains two kinds of Gradle build files:
  • Top-Level Build File: This is where you'll find the configuration options that are common to all the modules that make up your project.

  • Module-Level Build File: Each module has its own Gradle build file that contains module-specific build settings. You'll spend most of your time editing module-level build file(s) rather than your project's top-level build file.
To take a look at these build.gradle files, open Android Studio's Project panel (by selecting the Project tab) and expand the Gradle Scripts folder. In our sample project, the first two items in the list are your project's top-level and module-level build files.


The screenshot below gives you an idea of how the Gradle Scripts folder might look for a project with multiple modules.


Top-Level Gradle Build File:

  1. Every Android Studio project contains a single, top-level Gradle build file. This build.gradle file is the first item that appears in the Gradle Scripts folder and is clearly marked Project.
  2. Most of the time, you won't need to make any changes to this file, but it's still useful to understand its contents and the role it plays within your project. Below is an annotated version of a typical top-level build file.

//Project-level Gradle build files use buildscript to define dependencies.//
buildscript {
    repositories {
// jcenter() is a superset of mavenCentral(), it uses HTTPs to serve content, it is faster than mavenCentral() //
        jcenter()
    }
//This file relies on the jcenter repository.//
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'
//Project is dependent on version 1.5.0 of the Android plugin for Gradle.// 

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
//Defines the dependencies required by your application.//
    repositories {
        jcenter()
    }
}
//Application depends on the jCenter repository.//
task clean(type: Delete) {
    delete rootProject.buildDir
}

There are 3 main areas to this Android build file:

buildscript { ... } 

You will notice a new closure buildscript. This is nothing to do with App Engine and is generally used to specify dependencies that the build script will need to it. In our case, this script requires the App Engine Gradle library to be present and hence we are specifying it via the normal dependency and specifying from which repository to take it.
  • Configures the code driving the build. 
  • In this case, this declares that it uses the jCenter repository, 
  • There is a classpath dependency on a Maven artifact. This artifact is the library that contains the Android plugin for Gradle in version 1.3.1. 

Note: This only affects the code running the build, not the project. The project itself needs to declare its own repositories and dependencies.

allprojects { ... }

We have the dependencies that this project source code needs to compile.

task clean

  • Basically it is used to clean build system, It delete the build directory when run.
  • Task type is Delete (Can also be copy)
  •  When modify the file settings.gradle click sync, will delete the file rootProject.buildDir

Module-Level Gradle Build Files

In addition to the project-level Gradle build file, each module has a Gradle build file of its own. Below is an annotated version of a basic, module-level Gradle build file.

apply plugin: 'com.android.application'
//Since this project is an Android app, the build.gradle file utilises the Android plugin. if there is any library project  then we'll use apply plugin: 'com.android.library' as plugin //
android {
// The following section configures all your project’s Android-specific parameters, and tells Gradle which version of Android it should build your project with. If you’ve developed Android applications before, the following should all be familiar. //
// Signing configuration to generate signed app if you already have .jks file //
signingConfigs {
        config {
            keyAlias 'test'
            keyPassword 'test123'
            storeFile file('/home/shivang/Desktop/test.jks')
            storePassword 'test123'
        }
    }
    compileSdkVersion 21
//The API your project is targeting.// 
    buildToolsVersion "21.1.1"
////The version of the build tools you want to use.//
    defaultConfig {
        applicationId "com.example.jessica.myapplication"
//Defines your application’s ID. Note, earlier versions of the Android plugin used ‘packageName’ instead of ‘applicationID.’//
        minSdkVersion 16
//The minimum API required by your project.//
        targetSdkVersion 21
//The version of Android you’re developing your application for.//      
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
// add signing configuration for build //
           signingConfig signingConfigs.config
// ‘BuildTypes’ controls how your app is built and packaged. If you want to create your own build variants, you’ll need to add them to this section. //
            minifyEnabled true
            shrinkResources true
// Resource shrinking is the automatic removal of resources that are unused, at build time, in the packaged app, you have to enable minifyEnabled in order to turn on code shrinking.

// Gradle runs ProGuard during the build process.//
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
//Applies the default ProGuard settings from the Android SDK.// 

        }
// Generates Different variants of app //
 productFlavors {
        demo {
            applicationId = "com.example.myapplication.demo"
            resValue "string", "app_name", "Demo App"
        }
        full {
            applicationId = "com.example.myapplication.full"
            resValue "string", "app_name", "Full App"
        }
     }
    }

dependencies {
// A folder entirely dependent, All the jar file exist in libs directory will automatically included //
    compile fileTree(dir: 'libs', include: ['*.jar'])
// single file depends 
    compile Files ( 'libs / Android-Support-v4.jar' )
// Gradle dependency that points to the wearable app module, because users cannot browse and install apps directly on the wearable. If packaged properly, when users download the handheld app, the system automatically pushes the wearable app to the paired wearable.
    wearApp project(':wear')
// Testing dependencies
    testCompile 'junit:junit:4.12'
// Application format: packageName: artifactId: Version
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.google.android.gms:play-services:8.3.0'
    compile 'com.android.support:design:23.1.1'
// Use Android Archive //
   compile 'com.kevinpelgrims.library:library:1.0.0@aar'
// Using the @aar notation if you want to download the dependencies, you should add, otherwise it may skip some dependencies //
   transitive=true
   compile(name:'yourlibraryname', ext:'aar')
}

apply plugin:

  • The com.android.application plugin is applied. This is the plugin used for building Android applications.
  • if there is any library project  then we'll use apply plugin'com.android.library' as plugin

android { ... } 

  • configures all the parameters for the android build. 
  • This is the entry point for the Android DSL. 
  • By default, only the compilation target, and the version of the build-tools are needed. This is done with the compileSdkVersion and buildtoolsVersion properties.

Other Gradle Files:

In addition to the build.gradle files, your Gradle Scripts folder contains some other Gradle files. Most of the time you won't have to manually edit these files as they'll update automatically when you make any relevant changes to your project. However, it's a good idea to understand the role these files play within your project.


gradle-wrapper.properties (Gradle Version)

This file allows other people to build your code, even if they don't have Gradle installed on their machine. This file checks whether the correct version of Gradle is installed and downloads the necessary version if necessary. In our sample app,gradle-wrapper.properties contains the following:

distributionBase=GRADLE_USER_HOME
//Determines whether the unpacked wrapper distribution should be stored in the project, or in the Gradle user home directory.//
distributionPath=wrapper/dists
//The path where the Gradle distributions required by the wrapper are unzipped.//

zipStoreBase=GRADLE_USER_HOME

zipStorePath=wrapper/dists

distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip

//The URL where the correct version of Gradle should be downloaded from.//

settings.gradle

This file references all the modules that make up your project. Since our sample project has a single module, this file is very straightforward as you can see below.

include ':app'
or
include ':mobile', ':wear', ':tv', ':glass', ':mylibrary'

gradle.properties (Project Properties)

This file contains configuration information for your entire project. It's empty by default, but you can apply a wide range of properties to your project by adding them to this file.

// Used to speed up gradle build process //
//When configured, Gradle will run in incubating parallel mode.
org.gradle.parallel=true
//Gradle runs on the Java Virtual Machine (JVM) and uses several supporting libraries that require a non-trivial initialization time. As a result, it can sometimes seem a little slow to start. The solution to this problem is the Gradle Daemon: a long-lived background process that executes your builds much more quickly than would otherwise be the case.
org.gradle.daemon=true

local.properties (SDK Location)

This file tells the Android Gradle plugin where it can find your Android SDK installation. For example:

ndk.dir=/home/shivang/programFiles/android-sdk-linux/ndk-bundle
sdk.dir=/home/shivang/programFiles/android-sdk-linux

Note that local.properties contains information that's specific to the local installation of the Android SDK. This means that you shouldn't keep this file under source control.

Some Important Points:

Question 1: Set up compile dependencies in Android Studio in build.gradle. I mean that they not include into final APK.

this build.gradle works fine but i don't need 
lombok
library in apk in runtime;

apply plugin: 'android'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        minSdkVersion 10
        targetSdkVersion 16
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    } }

dependencies {
    compile 'com.android.support:appcompat-v7:+'
    compile 'org.projectlombok:lombok:1.12.2' }

And may be its possible to setup in global build.gradle file for all projects?

Answer:
Android Gradle plugin adds a 'provided' dependency scope for dependencies needed only for compile time that are not linked into the APK.
You specify it like this:
dependencies {
    provided 'org.projectlombok:lombok:1.12.2'
}
As for whether you can put it in the top-level build.gradle file to have it apply to all modules, I'm not certain. I tried putting it in the allprojects block, but Gradle told me that the default dependency handler didn't know what to do with it. So I'm guessing no, but if I get other information, I'll update this answer.


Reference Links:
http://www.tothenew.com/blog/gradle-android-studio/
http://stackoverflow.com/questions/21344692/how-to-set-up-compile-library-in-android-studio-lombok
http://rominirani.com/2014/08/15/gradle-tutorial-part-5-gradle-app-engine-plugin/
http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Product-flavors
Resource Shrinking
http://tools.android.com/tech-docs/new-build-system/resource-shrinking
Application Id and Package name
http://tools.android.com/tech-docs/new-build-system/applicationid-vs-packagename
Signing Android app
http://developer.android.com/tools/publishing/app-signing.html
http://stackoverflow.com/questions/31731014/what-does-transitive-true-in-gradle-exactly-do-w-r-t-crashlytics






Wednesday, December 2, 2015

Get Address of Center Point of Google Map Android


Here I am placing the code snippet that can get address of center point of visible google map. Here I am using OnCameraChangeListener that will give address when map drag.

private GoogleMap googleMap;
googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {

    @Override
    public void onCameraChange(CameraPosition arg0) {
     search_location_view_TV.setText("Getting Address...");

     VisibleRegion visibleRegion = googleMap.getProjection().getVisibleRegion();
     Point x = googleMap.getProjection().toScreenLocation(visibleRegion.farRight);
     Point y = googleMap.getProjection().toScreenLocation(visibleRegion.nearLeft);
     Point centerPoint = new Point(x.x / 2, y.y / 2);
     LatLng centerFromPoint = googleMap.getProjection().fromScreenLocation(centerPoint);

     Log.d("Punto x", "x:" + x.x + "y:" + x.y);
     Log.d("Punto y", "y:" + y.x + "y:" + y.y);
     Log.d("MapFragment: ", "Center From Point: Long: " + centerFromPoint.longitude + " Lat" + centerFromPoint.latitude);

     String addressString = getCompleteAddressString(centerFromPoint.latitude, centerFromPoint.longitude);
     System.out.println("addressString..................."+addressString);
     search_location_view_TV.setText(addressString);
    }
   });

private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
  String strAdd = "";
  Geocoder geocoder = new Geocoder(this, Locale.getDefault());
  try {
   List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
   if (addresses != null) {
    Address returnedAddress = addresses.get(0);
    StringBuilder strReturnedAddress = new StringBuilder("");

    for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
     strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
    }
    strAdd = strReturnedAddress.toString();
    Log.w("My Current loction address", "" + strReturnedAddress.toString());
   } else {
    Log.w("My Current loction address", "No Address returned!");
   }
  } catch (Exception e) {
   e.printStackTrace();
   Log.w("My Current loction address", "Canont get Address!");
  }
  return strAdd;
 }

Reference:

googling.