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.

Monday, November 30, 2015

Half Circular List View


There were a requirement to create a half circular list view in one of my application, There were many solutions over internet but no one satisfy the requirement, some are able to populate only image data and some are text data but I need to populate both in my list view. After goggling lots I got a solution that was really optimize and working fine and fulfilling the requirement. Here is a image that I want to develop.



Here I am sharing code that was working on eclipse, you can download here.

Reference:


Friday, November 27, 2015

How to authenticate the mobile number 

In the normal authentication flow, we use SMS to send OTP and Push Notification to get same OTP code to validate. But I think you want to send SMS without any SMS gateway. So you can try to write a java program that will send a SMS by using modem that have facility to send SMS like internet modem.

I found an API that provide Online validation of Phone number, Try this one: http://www.phone-validator.net/phone-number-online-validation-api.html
But you need your work Email id, not possible with free email address.
Reference:
Googling

Monday, November 16, 2015

Get Current Location using Android Studio With Android M Support


You can get Current location in Android M using Below code...
You can Download full source code here.

GPSTracker.java



package com.example.shivang.currentlocation;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.util.Log;

/** * Created by shivang on 09-11-2015. */

public class GPSTracker extends Service implements LocationListener{

    private final Context mContext;

    // flag for GPS status  
  boolean isGPSEnabled = false;

    // flag for network status  
  boolean isNetworkEnabled = false;

    boolean canGetLocation = false;

      Location location; // location     
 double latitude; // latitude   
 double longitude; // longitude

    // The minimum distance to change Updates in meters  
  private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    // The minimum time between updates in milliseconds  
  private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    // Declaring a Location Manager   
 protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }


    @TargetApi(Build.VERSION_CODES.M)
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(mContext.LOCATION_SERVICE);

            // getting GPS status     
       isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status   
         isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled     
       } else {
                this.canGetLocation = true;
                // First get location from Network Provider   
             if (isNetworkEnabled) {
//                    if(isPermission())      
              if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (mContext.checkSelfPermission(Manifest.permission.
ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || mContext.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            //DO OP WITH LOCATION SERVICE   
                         locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                        }
                    }else {
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);


                    }
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }
    /**     * Function to get latitude     * */    
public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude        return latitude;
    }

    /**     * Function to get longitude     * */    
public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude       
 return longitude;
    }

    /**     * Function to check if best network provider     * @return boolean     * */    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**     * Function to show settings alert dialog     * */ 
   public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title       
 alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message       
 alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // Setting Icon to Dialog      
  //alertDialog.setIcon(R.drawable.delete);
        // On pressing Settings button       
 alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button      
  alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message      
  alertDialog.show();
    }

    @Override  
  public void onLocationChanged(Location location) {
    }

    @Override   
 public void onProviderDisabled(String provider) {
    }

    @Override   
 public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }


    @Nullable   
 @Override   
 public IBinder onBind(Intent intent) {
        return null;
    }

    public Location getLocationUsingCriteria()  {

        locationManager = (LocationManager) mContext.getSystemService(mContext.LOCATION_SERVICE);
        android.location.Criteria criteria = new android.location.Criteria();
        String best = locationManager.getBestProvider(criteria, true);
        System.out.println("Best..................."+ best);

        //since you are using true as the second parameter, you will only get the best of providers which are enabled.      
  canGetLocation = true;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (mContext.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || mContext.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                //DO OP WITH LOCATION SERVICE             
   location = locationManager.getLastKnownLocation(best);
            }
        }else {
            location = locationManager.getLastKnownLocation(best);
        }

        return location;
    }
}


 

MainActivity.java


package com.example.shivang.currentlocation;

import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GPSTracker gpsTracker = new GPSTracker(this);

        if(gpsTracker.canGetLocation()){
//            Location location = gpsTracker.getLocation(); 
           Location location = gpsTracker.getLocationUsingCriteria();
            Toast.makeText(this, gpsTracker.getLatitude() +  " : " + gpsTracker.getLongitude(), Toast.LENGTH_LONG).show();

        }else{
            Toast.makeText(this, "Unable to get location!", Toast.LENGTH_LONG).show();
    gpsTracker.showSettingsAlert();
        }


//        location.getLatitude();//     
   location.getLongitude();



    }

}
permission:
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

Reference:
Googling

Tuesday, September 22, 2015

RoboGuice: (Android findViewById() vs @Inject View)


Roboguice is a dependency injection framework for Android applications, that brings the simplicity and ease of Dependency Injection to Android, using Google’s own Guice library. It smoothes out some of the wrinkles in your Android app development experience make things simple and fun. Do you always forget to check for null when you getIntent().getExtras()? RoboGuice 2 will help you. Think casting findViewById() to a TextView shouldn’t be necessary? RoboGuice is on it.
Using RoboGuice, you can inject your View, Resource, System Service, or any other object. RoboGuice can help you to slim down application code. Less code means less chances of issues/bugs and can help you to save efforts required to write or modify particular code in a project. It helps you to generate readable code which could be easier to follow.
Let’s look at different usage of RoboGuice library.

Usage of RoboGuice library:

  • Views Injection:: To initialize views, use @InjectViews, for example: @InjectView(R.id.textView1) TextView textView1;
  • Resources Injection: To initialize and get resources, use @InjectResources, for example: @InjectResource(R.string.app_name) String name;
  • System services Injection: To initialize and access system services, use @Inject, for example: @Inject LayoutInflater inflater;
  • POJO object Injection: To inject and initialize POJO object, use @Inject, for example: @Inject Foo foo;
Let’s look at an example of general activity code:
public class TestActivity extends Activity{
    TextView textView1;
    TextView textView2;
    ImageView imageView1;
    String name;
    Drawable icLauncher;
    LocationManager locManager;
    LayoutInflater inflater;
    NotificationManager notifyManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_test);
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);
        imageView1 = (ImageView) findViewById(R.id.imageView1);
        name = getString(R.string.app_name);
        icLauncher = getResources().getDrawable(R.id.ic_launcher);
        locManager = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);
        inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        notifyManager = (NotificationManager)        getSystemService(Activity.NOTIFICATION_SERVICE);
        textView1.setText("Hello World! RoboGuice demo");
    }
}

Let’s check the magic of RoboGuice and let’s slim down the code.

Using RoboGuice

To use RoboGuice for the dependency injection, you are required to extends eitherRoboActivity or RoboFragment.
public class TestActivity extends RoboActivity{


    @InjectView(R.id.textView1) TextView textView1;

    @InjectView(R.id.textView2) TextView textView2;
    @InjectView(R.id.imageView1) ImageView imageView1;
    @InjectResource(R.string.app_name) String name;
    @InjectResource(R.drawable.ic_launcher) Drawable icLauncher;
    @Inject LocationManager locManager;
    @Inject LayoutInflater inflater;
    @Inject NotificationManager notifyManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_test);
        textView1.setText(name);
    }
}
Benefits of using RoboGuice
  • No need to initialize views, if you want then Inject it using @InjectViews
  • No need to initialize System service. If you need then Inject it using @Inject
  • No need to initialize Drawable, string and other resources. If you require then Inject it using @InjectResource
  • All of these above practices helps you to slim down the code.
  • Less code => Less chances of bugs/issues
  • Less code => Android developer can save coding efforts and can focus fully on actual business logic of android app

RoboGuice and ActionBarSherlock

As I have mentioned earlier in alert box that you are required to extend either RoboActivity or RoboFragment to use RoboGuice in either Activity or Fragment particularly. But what if you have included ActionBarSherlock in your project to manage compatibility? The problem is you have extended either SherlockActivity or SherlockFragmentActivity for your activity or fragment particularly and now the situation is we could not use RoboGuice with ActionBarSherlock.
But There is one solution for it too, you have to define custom base classes for Activities and Fragments to use RoboGuice and ActionBarSherlock both.
You can download base classes from here: https://github.com/rtyley/roboguice-sherlock or download a JAR file for the same: RoboGuice+Sherlock.jar, include either of them in your project.
You can download a sample code here.

Reference:

Wednesday, September 16, 2015

Sending email with attachment using JavaMail API


For sending email with attachment, JavaMail API provides some useful classes like BodyPart, MimeBodyPart etc.

For better understanding of this example, learn the steps of sending email using JavaMail API first.
For sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar
download these jar files (or) go to the Oracle site to download the latest version.

Sending email with attachment using JavaMail API


There are total 7 steps for sending attachment with email. They are:
  1. Get the session object
  2. compose message
  3. create MimeBodyPart object and set your message text
  4. create new MimeBodyPart object and set DataHandler object to this object
  5. create Multipart object and add MimeBodyPart objects to this object
  6. set the multiplart object to the message object
  7. send message

Example of sending email with attachment using JavaMail API

import java.util.*;  
import javax.mail.*;  
import javax.mail.internet.*;  
import javax.activation.*;  
  
class SendAttachment{  
 public static void main(String [] args){  
  
  String to="example@gmail.com";//change accordingly  
  final String user="example@gmail.com";//change accordingly  
  final String password="xxxxx";//change accordingly  
   
  //1) get the session object    

//GMail via TLS
 Properties properties = System.getProperties();  
 properties.put("mail.smtp.host", "smtp.gmail.com");  
 properties.put("mail.smtp.auth", "true");  
 properties.put("mail.transport.protocol", "smtps");
 properties.put("mail.smtp.port", "587");
 properties.put("mail.smtp.starttls.enable", "true");
 // GMail via SSL

/*properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "465");*/
   Session session = Session.getDefaultInstance(properties,  
   new javax.mail.Authenticator() {  
   protected PasswordAuthentication getPasswordAuthentication() {  
   return new PasswordAuthentication(user,password);  
   }  
  });  
     
  //2) compose message     
  
try{  
    MimeMessage message = new MimeMessage(session);  
    message.setFrom(new InternetAddress(user));  
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
    message.setSubject("Message Aleart");  
      
    //3) create MimeBodyPart object and set your message text     

    BodyPart messageBodyPart1 = new MimeBodyPart();  
    messageBodyPart1.setText("This is message body");  
      
    //4) create new MimeBodyPart object and set DataHandler object to this object      

    MimeBodyPart messageBodyPart2 = new MimeBodyPart();  
  
    String filename = "SendAttachment.java";//change accordingly  
    DataSource source = new FileDataSource(filename);  
    messageBodyPart2.setDataHandler(new DataHandler(source));  
    messageBodyPart2.setFileName(filename);  
     
     
    //5) create Multipart object and add MimeBodyPart objects to this object      

    Multipart multipart = new MimeMultipart();  
    multipart.addBodyPart(messageBodyPart1);  
    multipart.addBodyPart(messageBodyPart2);  
  
    //6) set the multiplart object to the message object  

    message.setContent(multipart );  
     
    //7) send message  

    Transport.send(message);  
   
   System.out.println("message sent....");  
   }catch (MessagingException ex) {ex.printStackTrace();}  
 }  
}

You can download full source code Here.