Android | Get Last (Current) Location

get-location In a previous post Android |Get Current Location & Location Updates | Location Services API Tutorial , we have seen how to get current location using older android APIs. Google introduced a new API (fused location provider) to get device location using the Google Play Services. Using the new API, you can request the last known location of the user's device.

"In most cases, you are interested in the user's current location, which is usually equivalent to the last known location of the device. "

Environment & Tools

  • Windows 7
  • Eclipse ADT
  • Nexus 5

Note: If you have an existing app that connects to Google Play services with a subclass of GooglePlayServicesClient, you should migrate to GoogleApiClient as soon as possible.

About this Sample App

The code below is for an app that will get current location and display Lat & Long on the screen.

get-location

( 1 ) Create new Android Project

  • Application Name: Get Last Location
  • Project Name: android-get-last-location-fused-api
  • Package Name: com.hmkcode.locations

( 2 ) Set Up Google Play Services

( 3 ) AndroidManifest.xml

  • In AndroidManifest.xml Add the following tag as a child of the <application> element:

    <meta-data android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
    

  • Also, add the following permissions tags as a child of the <manifest> element:

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

  • See the complete of AndroidManifest.xml

( 4 ) Connect to Google Play Services & Get the Last Known Location

  • In MainActivity.java do the following:
    • Implement ConnectionCallbacks & OnConnectionFailedListener.
    • Override the following methods onConnectionFailed(), onConnected() & onConnectionSuspended().
    • Define a method buildGoogleApiClient()to create an instance of the Google Play services API client using GoogleApiClient.Builder.


  • MainActivity.java will work as following:
    • When the application starts it will call onCreate() method.
    • onCreate() will set the layout of the main activity and connect the Play service.
    • If the connection to the Paly Service is successful onConnect() method will be called.
    • onConnect() will call getLastLocation() and display Lat & Long.
    • If the connection to Play Service is failed or suspended other methods will be called.
package com.hmkcode.locations;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationServices;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements 
    ConnectionCallbacks, OnConnectionFailedListener {

    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    TextView tvLatlong;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tvLatlong = (TextView) findViewById(R.id.tvLatlong);
        
        buildGoogleApiClient();
        
        if(mGoogleApiClient!= null){
            mGoogleApiClient.connect();
        }
        else
            Toast.makeText(this, "Not connected...", Toast.LENGTH_SHORT).show();

            
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        Toast.makeText(this, "Failed to connect...", Toast.LENGTH_SHORT).show();
        
    }

    @Override
    public void onConnected(Bundle arg0) {
        
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        
        if (mLastLocation != null) {
            tvLatlong.setText("Latitude: "+ String.valueOf(mLastLocation.getLatitude())+"Longitude: "+
                    String.valueOf(mLastLocation.getLongitude()));
        }

    }

    @Override
    public void onConnectionSuspended(int arg0) {
        Toast.makeText(this, "Connection suspended...", Toast.LENGTH_SHORT).show();
        
    }
    
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    }
}

Source Code @ GitHub