Android Location using Google Play Services

Google introduced FusedLocationApi in google Play Services to get location and location updates, Google play services provide location updates much efficiently.

FusedLocationApi connects with GoogleApiClient to provide location and location updates.

So, Let’s Start.

In this tutorial, I will show you how to get Location from google play services in your application.

For Eclipse ADT users add download google play services library by following steps:-

1.Copy the library project at <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/ to the location where your project.

2.Import the library project into your project by File->Import, select Android, Existing android code into your workspace and browse to the copy of project and then click Finish.

For Android Studio users add  dependency in your Gradle file

compile ‘com.google.android.gms:play-services:8.4.0’

To use Google Play Services  in our application we need GoogleMapsApi_Key

you can get this key from google developers console  from here.

we use this API key in AndroidManifest.xml file

Carefully add following permissions in AndroidManifest.xml

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

So, now we are ready to create New Project to get Location.

1.Open Eclipse or Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.

2. Now Create layout file for MainActivity.java that will be our mainscreen

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/getlocation"
        android:text="GetLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/getlocationupdates"
        android:text="getLocationUpdates"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/lat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/log"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

3. Now we need to implement three Listeners ConnectionCallbacks, OnConnectionFailedListener and Location Listener to connect googleapiclient and get location as well as Location updates in MainActivity.java

4.in this we will first check the availability of Google Play Services by calling checkGooglePlayServices().

5.If googlePlayServices are available, then we will build googleApiClient by calling setUpGoogleClient() and call createLocationRequest() to get Location updates.

6. Once googleApiClient is connected then we will call displayMyLocation() to display current Location.

7. createLocationRequest() is used to get Location Updates by setting location updating distance and location updating time.

8. getPeriodicLocationUpdates() will display Location Updations.

MainActivity.java

package com.coderzpassion.gplaceslocation;

import android.app.Activity;
import android.content.ComponentCallbacks;
import android.location.Location;
import android.location.LocationListener;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

    private Location mylocation;
    // google client for connecting to Google Api
    private GoogleApiClient googleApiClient;
    // flag to get location updates
    private boolean getLocationUpdates=false;
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
    //for location request
    private LocationRequest locationRequest;
    // for location updates
    private int locationupdate = 8000; //in milliseconds
    private int locationdistance = 10; // in meters

    //button to get my current location, getlocation updates
    Button getmylocation,getlocationupdates;
    // textviews to show latitude and longitude
    TextView lat, log;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getmylocation = (Button) findViewById(R.id.getlocation);
        lat = (TextView) findViewById(R.id.lat);
        log = (TextView) findViewById(R.id.log);
        getlocationupdates=(Button)findViewById(R.id.getlocationupdates);
        getlocationupdates.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
           getPeriodicLocationUpdates();

            }
        });
        //check if google play services available
        if (checkGooglePlayServices()) {
            // set up google client
            setUpGoogleClient();

            //set Location Request
            createLocationRequest();
        }

        getmylocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                displayMyLocation();
            }
        });

    }

    public boolean checkGooglePlayServices() {
        GoogleApiAvailability gApi = GoogleApiAvailability.getInstance();
        int resultCode = gApi.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (gApi.isUserResolvableError(resultCode)) {
                gApi.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(this, "Google Play Services not Avaliable", Toast.LENGTH_LONG).show();
                finish();
            }
            return false;
        }
        return true;
    }

    public void setUpGoogleClient() {
        // Create an instance of GoogleAPIClient.
        if (googleApiClient == null) {
            googleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
    }

    public void displayMyLocation() {
        mylocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (locationRequest != null) {
            lat.setText("latitude" + String.valueOf(mylocation.getLatitude()));
            log.setText("longitude" + String.valueOf(mylocation.getLongitude()));
        }

    }

    @Override
    public void onConnected(Bundle bundle) {
        displayMyLocation();
    }

    @Override
    public void onConnectionSuspended(int i) {
        googleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    protected void onStart() {
        super.onStart();
        if (googleApiClient != null) {
            googleApiClient.connect();
        }

    }

    protected void onStop() {
        if (googleApiClient != null) {
            googleApiClient.disconnect();
        }
        super.onStop();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    protected void createLocationRequest() {
        locationRequest = new LocationRequest();
        locationRequest.setInterval(locationupdate); //in milliseconds
        locationRequest.setFastestInterval(5000); //in milliseconds
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setSmallestDisplacement(locationdistance);
    }

    protected void startLocationUpdates() {

        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest,this);
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
    }

    @Override
    public void onLocationChanged(Location location) {
         mylocation=location;
        displayMyLocation();
    }

    // get periodic updates
    private void getPeriodicLocationUpdates() {
        if (!getLocationUpdates) {
            // Changing the button text
            getlocationupdates.setText("Stop Location Updates");

            getLocationUpdates = true;

            // Starting the location updates
            startLocationUpdates();

            Log.d("MainActivity", "Periodic location updates started!");

        } else {
            // Changing the button text to start location updtes
            getlocationupdates.setText("Start Location Updates");

            getLocationUpdates = false;

            // stop the location updates
            stopLocationUpdates();

            Log.d("MainActivity", "Periodic location updates stopped!");
        }
    }

}

Output

Screenshot_2016-02-28-13-54-42