Thursday, 24 September 2015

Building Apps with Over 65K Methods

As the Android platform has continued to grow, so has the size of Android apps. When your application and the libraries it references reach a certain size, you encounter build errors that indicate your app has reached a limit of the Android app build architecture.


About the 65K Reference Limit

Android application (APK) files contain executable byte code files in the form of Dalvik  Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536, including Android framework methods, library methods, and methods in your own code. Getting past this limit requires that you configure your app build process to generate more than one DEX file, known as a multidex configuration.

Multidex support prior to Android 5.0

Versions of the platform prior to Android 5.0 use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can use the multidex support library, which becomes part of the primary DEX file of your app and then manages access to the additional DEX files and the code they contain.

Multidex support for Android 5.0 and higher

Android 5.0 and higher uses a runtime called ART which natively supports loading multiple dex files from application APK files. ART performs pre-compilation at application install time which scans for classes(..N).dex files and compiles them into a single .oat file for execution by the Android device. For more information on the Android 5.0 runtime, see Introducing ART.

Avoiding the 65K Limit


Before configuring your app to enable use of 65K or more method references, you should take steps to reduce the total number of references called by your app code, including methods defined by your app code or included libraries. The following strategies can help you avoid hitting the dex reference limit:
  • Review your app's direct and transitive dependencies - Ensure any large library dependency you include in your app is used in a manner that outweighs the amount of code being added to the application. A common anti-pattern is to include a very large library because a few utility methods were useful. Reducing your app code dependencies can often help you avoid the dex reference limit.
  • Remove unused code with ProGuard - Configure the ProGuard settings for your app to run ProGuard and ensure you have shrinking enabled for release builds. Enabling shrinking ensures you are not shipping unused code with your APKs.
Using these techniques can help you avoid the build configuration changes required to enable more method references in your app. These steps can also decrease the size of your APKs, which is particularly important for markets where bandwidth costs are high.

Configuring Your App for Multidex with Gradle


The Android plugin for Gradle available in Android SDK Build Tools 21.1 and higher supports multidex as part of your build configuration. Make sure you update the Android SDK Build Tools tools and the Android Support Repository to the latest version using the SDK Manager before attempting to configure your app for multidex.
Setting up your app development project to use a multidex configuration requires that you make a few modifications to your app development project. In particular you need to perform the following steps:
  • Change your Gradle build configuration to enable multidex
  • Modify your manifest to reference the MultiDexApplication class
Modify your app Gradle build file configuration to include the support library and enable multidex output, as shown in the following Gradle build file snippet:
public class App extends android.support.multidex.MultiDexApplication {
//your code here
}

Limitations of the multidex support library

The multidex support library has some known limitations that you should be aware of and test for when you incorporate it into your app build configuration:
  • The installation of .dex files during startup onto a device's data partition is complex and can result in Application Not Responding (ANR) errors if the secondary dex files are large. In this case, you should apply code shrinking techniques with ProGuard to minimize the size of dex files and remove unused portions of code.
  • Applications that use multidex may not start on devices that run versions of the platform earlier than Android 4.0 (API level 14) due to a Dalvik linearAlloc bug (Issue 22586). If you are targeting API levels earlier than 14, make sure to perform testing with these versions of the platform as your application can have issues at startup or when particular groups of classes are loaded. Code shrinking can reduce or possibly eliminate these potential issues.
  • Applications using a multidex configuration that make very large memory allocation requests may crash during run time due to a Dalvik linearAlloc limit (Issue 78035). The allocation limit was increased in Android 4.0 (API level 14), but apps may still run into this limit on Android versions prior to Android 5.0 (API level 21).
  • There are complex requirements regarding what classes are needed in the primary dex file when executing in the Dalvik runtime. The Android build tooling updates handle the Android requirements, but it is possible that other included libraries have additional dependency requirements including the use of introspection or invocation of Java methods from native code. Some libraries may not be able to be used until the multidex build tools are updated to allow you to specify classes that must be included in the primary dex file.

Monday, 14 September 2015

Discussions - Marshmallow Android 6.0 with new Features

Marshmallow Android 6.0 with new Features

Google Finally announced that the next generation Android M is “Marshmallow”. This news was announced by Dave Burke. The Google will soon allow developers to upload apps base on Android 6.0 to be uploaded on the PlayStore.

Android 6.0 is mainly aimed at stability and performance improvements, and will bring new features such as – Fingerprint Scanner, Android Pay , MultiWindow , Tap on Now, New app Permissions Model, Support for the USB Type-C, Doze for Battery .

Here i describe few features that has been introduced in Marshmallow :

1) Support Fingerprint: API for Fingerprint support will be provided and if developer want they can incorporate the API into their app.

2) App Permission: How many time you want to restrict the permission that are given to apps. Now in Android M the new API allows users to decide what permission they want to give to any particular app.

3) Google Now: Now searching easy is Easy on Android M. It is a voice assisted search that allows you to search anything without leaving the app currently running. I think that one is best facility.

Main Feature
4) Doze for Battery : This battery saving feature of Marshmallow that will allow the phone battery to last as much as two and half time longer than Lollipop. It will detect if the phone is not touched or moved for a long period of time it will go to sleep, hence saving precious battery.

Lollipop Android 5.0 with new Features:

1.RecylcerView
2.CardView
3.Snack Bar
4.co-ordinating layout
5.TextInputLayout (EditText)
6. elevation
7.Ripple effect
8. FAB
9.SwipeRefresh Layout
10.alert Dialog
11.Vector Drawables
12.Activity Transitons
13. Themes
14.Navigation Drawer
15.Color Pallete 
16. Layout Manager(stagged, Grid)
17.AppBarLayout
18.CollapsingToolbarLayout
19.collabration layout 
20.Paralllax Model
21.reveal animations

Difference between asynctask and service in android

By default, a Service object runs on the main thread, also called the foreground thread. The only real difference between a Service and an Activity is that a Service doesn't have a UI. An *IntentService* runs on a separate thread, but its thread stops once it's processed every instruction in its main method, so by default it doesn't maintain its state. 

An AsyncTask is initiated by the main thread, but runs in a separate thread. However, if the Activity that started the AsyncTask is moved to the background, the AsyncTask stops, and its work may not be completed. 
Remember that the main thread runs your UI. Don't block it with long-running operations, or the user will see Application Not Responding (ANR). In addition, more recent versions of the platform don't allow you to run network operations on the main thread. 

For operations that you want to run in the background, but you're willing to restart if your Activity disappears, use an AsyncTask. For a discrete operation that you want to run to completion without communication, using a background thread, use IntentService. 

If you want a "presence" for your app that continues to chug along, perhaps doing nothing, even when your app isn't in the foreground, consider a bound Service.

Friday, 28 August 2015

Setting fixed height for Listview

Setting fixed height for Listview:

 

 In this post we have learn about to setting a fixed height for List view (i.e) List view having 20 list items. But displaying only 4 items. once we delete the item, the next item has to displayed.


Code:

 public  void SetCustomHeightForListView(ListView listView,int size) {
ListAdapter list_adapter = listView.getAdapter();
 ViewGroup.LayoutParams layoutParams =   listView.getLayoutParams();
int UNBOUNDED = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int grossElementHeight = 0;
        for (int g = 0; g <size; g++) {
            View childView = list_adapter.getView(g, null, listView);
            childView.measure(UNBOUNDED, UNBOUNDED);
            grossElementHeight += childView.getMeasuredHeight();
        }
        layoutParams.height = grossElementHeight;
        listView.setLayoutParams(layoutParams);
        listView.invalidate();
    }

 

To get full code

Click Here

 

 OutPut:

Before Deleting (Shows First Four Items-  fixed height for List view )

 

 

 

After Deleting (Shows Four Items- fixed height for Listview )

 

 

Thursday, 27 August 2015

Adding Views Dynamically

In this example creating some UI elements on screen on run time.

XML Code:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/shadow_common"
    android:padding="5dp"
    android:orientation="horizontal"
    android:visibility="visible">

    <RelativeLayout
        android:id="@+id/closelayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RelativeLayout
            android:id="@+id/textLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:gravity="center"
                android:padding="5dp"
                android:textSize="12dp"
                android:text="Aminities" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/textLayout" >

            <TextView
                android:id="@+id/edit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/circul_shape_black"
                android:gravity="center"
                android:text=""
                android:textColor="@android:color/black"
                android:textSize="8sp" />

            <ImageView
                android:id="@+id/editfont"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:src="@android:drawable/ic_delete"
                android:textSize="8dp" />
        </RelativeLayout>
    </RelativeLayout>


</LinearLayout>


Java Code:


  add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txt=text.getText().toString();
                flowContainer.setVisibility(View.VISIBLE);
                flowContainer.setOrientation(LinearLayout.VERTICAL);
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                final View addView = layoutInflater.inflate(R.layout.view_locality_selection, null);
                TextView textOut = (TextView) addView.findViewById(R.id.textout);
                textOut.setText("" + txt);
                text.setText("");
                addView.setTag(txt);
                //Typeface font = Typeface.createFromAsset(getAssets(), "fonts/AndroidFont.ttf");
                RelativeLayout buttonCLick = (RelativeLayout) addView.findViewById(R.id.closelayout);
                ImageView buttonRemove = (ImageView) addView.findViewById(R.id.editfont);
                //buttonRemove.setTypeface(font);

                buttonCLick.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        flowContainer.removeView(addView);
                        String s = addView.getTag().toString();



                    }
                });

                flowContainer.addView(addView);

            }
        });

To get Full code:

View Pager and Adding Text View Dynamically

The ViewPager is the widget that allows the user to swipe left or right to see an entirely new screen. 

In this tutorial, you will learn how to implement a viewpager gallery of images and Left, Right arrow icon in your Android application

Sample code:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="@drawable/roundcorners_darkgrey_border"
    android:orientation="vertical">

    <TextView
        android:id="@+id/cd_tv_city"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:text="Matching Properties"
        android:textColor="#000000"
        android:textSize="18dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="2dp"
        android:text="Individual: Raja K"
        android:textColor="#000000" />


    <FrameLayout
        android:id="@+id/view_pager_image_layout"
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:orientation="vertical">

        <android.support.v4.view.ViewPager
            android:id="@+id/view_pager"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" />

        <RelativeLayout
            android:id="@+id/imageview_left_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left|center_vertical"
            android:visibility="gone">

            <TextView
                android:layout_width="40dp"
                android:layout_height="50dp"
                android:background="@drawable/white_shadow"
                android:gravity="center"
                android:textColor="@android:color/white"
                android:textSize="25dp" />

            <TextView
                android:id="@+id/arrow"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:shadowColor="#000000"
                android:shadowDx="2"
                android:shadowDy="1"
                android:shadowRadius="3"
                android:text="@string/unit_left_arrow_icon"
                android:textColor="@android:color/white"
                android:textSize="16dp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/imageview_right_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right|center_vertical"
            android:visibility="gone">

            <TextView
                android:layout_width="40dp"
                android:layout_height="50dp"
                android:background="@drawable/white_shadow_rgt"
                android:gravity="center"
                android:textColor="@android:color/white"
                android:textSize="25dp" />

            <TextView
                android:id="@+id/arrow1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:shadowColor="#000000"
                android:shadowDx="1"
                android:shadowDy="2"
                android:shadowRadius="3"
                android:text="@string/unit_right_arrow_icon"
                android:textColor="@android:color/white"
                android:textSize="16dp" />
        </RelativeLayout>


    </FrameLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:orientation="horizontal"
        android:weightSum="10">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="5"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/view_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/icon_star_active"
                android:textColor="#33B5E5" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="View"
                android:textColor="#33B5E5" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="5"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/short_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/icon_star_active"
                android:textColor="#33B5E5" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="ShortList"
                android:textColor="#33B5E5" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/phone_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/dedicatedtelephonelineavailable_icon"
                android:textColor="#33B5E5" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Express Interest"
                android:textColor="#33B5E5" />
        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/bottom_layer"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:orientation="horizontal">

    </LinearLayout>

</LinearLayout>

Java code:


package androidapp.test.com.viewpagerproject;

import android.app.ActionBar;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.nio.charset.MalformedInputException;
import java.util.ArrayList;

public class MainActivity extends Activity {
    ViewPager viewPager;
    private ArrayList<ImageItem> Image_list;
    private RelativeLayout leftNavigate;
    private RelativeLayout rightNavigate;
    private TextView view_image, short_image, phone_image, star;
    private LinearLayout lm;
    // private TextView image1,image2,image3,image4,image5;
    //  Typeface tfAndroidFont;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        leftNavigate = (RelativeLayout) findViewById(R.id.imageview_left_image);
        rightNavigate = (RelativeLayout) findViewById(R.id.imageview_right_image);
        view_image = (TextView) findViewById(R.id.view_image);
        short_image = (TextView) findViewById(R.id.short_image);
        phone_image = (TextView) findViewById(R.id.phone_image);


        // view_image.setTypeface(tfAndroidFont);
        // phone_image.setTypeface(tfAndroidFont);
        // short_image.setTypeface(tfAndroidFont);
        Image_list = new ArrayList<ImageItem>();
        for (int i = 0; i < 5; i++) {
            ImageItem img = new ImageItem();
            if (i == 0) img.img_url = R.drawable.me;
            if (i == 1) img.img_url = R.drawable.me2;
            if (i == 2) img.img_url = R.drawable.me;
            if (i == 3) img.img_url = R.drawable.me2;
            if (i == 4) img.img_url = R.drawable.me;
            img.title = "Android";
            img.id = "Easy";
            Image_list.add(img);
        }
        //Create four
        lm = (LinearLayout) findViewById(R.id.bottom_layer);
        dynamicView(0);

        if (Image_list.size() == 1) {
            rightNavigate.setVisibility(View.GONE);
            leftNavigate.setVisibility(View.GONE);

        } else {
            leftNavigate.setVisibility(View.GONE);
            rightNavigate.setVisibility(View.VISIBLE);
        }
        PageListener pageListener = new PageListener();
        viewPager.setOnPageChangeListener(pageListener);

        ImageAdapter adapter = new ImageAdapter(MainActivity.this, Image_list);
        viewPager.setAdapter(adapter);

        leftNavigate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
            }
        });

        rightNavigate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
            }
        });


    }


    private class PageListener extends ViewPager.SimpleOnPageChangeListener {
        @Override
        public void onPageSelected(int position) {
            try {
                // Log.i("View Pager", "page selected " + position);

                int currentPage = position + 1;
                lm.removeAllViews();
                dynamicView(position);
                if (currentPage == 1) {
                    leftNavigate.setVisibility(View.GONE);
                    rightNavigate.setVisibility(View.VISIBLE);
                } else if (currentPage == Image_list.size()) {

                    leftNavigate.setVisibility(View.VISIBLE);
                    rightNavigate.setVisibility(View.GONE);
                } else {
                    leftNavigate.setVisibility(View.VISIBLE);
                    rightNavigate.setVisibility(View.VISIBLE);
                }


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


    public void dynamicView(int pos) {
        for (int j = 0; j < Image_list.size(); j++) {
            LinearLayout ll = new LinearLayout(MainActivity.this);
            ll.setOrientation(LinearLayout.HORIZONTAL);
            // Create TextView
            star = new TextView(MainActivity.this);
            star.setText("S");
            //  star.setTypeface(tfAndroidFont);
            if (pos == j) {
                star.setTextColor(Color.BLUE);
            } else {
                star.setTextColor(Color.RED);
            }

            star.setTextSize(25);
            star.setPadding(10, 0, 0, 0);
            star.setId(j);
            ll.addView(star);
            lm.addView(ll);
            star.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_LONG).show();
                    viewPager.setCurrentItem(v.getId());
                }
            });

        }

    }
}

To Get Full Code:

Monday, 8 June 2015

Android Location API Using Google Play Services (Fuesd Location API)

The Fused Location Provider intelligently manages the underlying location technology and gives us the best location according to our needs.
WHY USE
We could choose one of the location providers (network or GPS) and request location updates or set up proximity alert. But there were two main issues with this approach:
1. In case we need to define precise location, we had to switch between network and GPS location providers (as GPS doesn’t work indoors).
2. Proximity alerts were used to notify a user about proximity to a location, and this took its toll on the battery life.
ADVANTAGE OF USING THIS API
1. Simple APIs: Lets us specify high-level needs like “high accuracy” or “low power”, instead of having to worry about location providers.
2. Immediately available: Gives our apps immediate access to the best, most recent location.
3. Power-efficiency: Minimizes out app’s use of power. Based on all incoming location requests and available sensors, fused location provider chooses the most efficient way to meet those needs.
4. Versatility: Meets a wide range of needs, from foreground uses that need highly accurate location to background uses that need periodic location updates with negligible power impact.
Note : Make sure Google Play services is properly installed and working in our device. Please don’t test this location api in emulator because this api is not working in the emulator.
WAY TO USE
1. Import Google Play Services from android SDK (../sdk/extras/google/google_play_service/libproject/google-play-services_lib) as a library in our application.

2.
 Declare the permission in the manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Android has two location permissions, ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION. The permission we choose affects the accuracy of the location updates we receive. For example, If we request only coarse location permission, Location Services obfuscates the updated location to an accuracy that’s roughly equivalent to a city block.
Requesting ACCESS_FINE_LOCATION implies a request for ACCESS_COARSE_LOCATION.
3. There is two main class which are most important in this server
3.1 com.google.android.gms.location.LocationClient : Stores the current instantiation of the location client.
3.2 com.google.android.gms.location.LocationRequest : A data object that contains quality of service parameters for requests to the LocationClient.
4. Location service callbacks : Before we request location updates, we must first implement the interfaces that Location Services uses to communicate connection status to our app:
4.1 com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks: Specifies methods that Location Services calls when a location client is connected or disconnected.
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "+ result.getErrorCode());
}
@Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
}
4.2 com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener:Specifies a method that Location Services calls if an error occurs while attempting to connect the location client.

HOW TO USE
1. Connecting LocationClient to Google api. After connecting locationClient, we are able to get location.
2. Retrieving the current location
3. Retrieving the location update at particular time interval or particular distance or both.
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
During the Google IO presentation, a chart was presented showing effect of different priorities of the recognition algorithm as tested multiple times on Galaxy Nexus.
PriorityTypical location
update interval
Battery drain
per hour (%)
Accuracy
HIGH_ACCURACY5 seconds7.25%~10 meters
BALANCED_POWER20 seconds0.6%~40 meters
NO_POWERN/Asmall~1 mile

2. Retrieving the current location :
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
lblLocation.setText(latitude + ", " + longitude);
} else {
lblLocation.setText("(Couldn't get the location. Make sure location is enabled on the device)")
  }
}
The return value is the best, most recent location, based on the permissions our app requested and the currently-enabled location sensors.
Before we create the location client, implement the interfaces that Location Services uses to communicate with our app:
Reference : https://developer.android.com/training/location/retrieve-current.html
3. Retrieving Location Updates : To get periodic location updates from Location Services, we send a request using a location client. Depending on the form of the request, Location Services either invokes a callback method and passes in a Location object, or issues an Intent that contains the location in its extended data. The accuracy and frequency of the updates are affected by the location permissions we’ve requested and the parameters we pass to Location Services with the request.
@Override
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
Toast.makeText(getApplicationContext(),"Location changed!",Toast.LENGTH_SHORT).show();
// Displaying the new location on UI
displayLocation();
}
To Get Full Code:  Click Here