Android |Get Current Location & Location Updates | Location Services API Tutorial

android-location-apiLocation Services API enables you to build location-aware Android application without going into the details of the underlying technologies. Location Services maintains user’s current location so your app just needs to get it from location client. The accuracy of the location depends on the active location sensors and location permissions requested in the Manifest file. Also, the API allows you to get the user’s updated location at regular intervals.

the content of this post is old, go to the new post: Android | Get Last (Current) Location

Note: Google introduced a new API (fused location provider) to get device location using the Google Play Services. 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.

Environment & Tools

( 1 ) Create a new Android Project

  • Application Name: Get Current Location
  • Project Name: android-get-current-location
  • Package Name: com.hmkcode.android.location

( 2 ) Activity Layout

The layout for this example is so simple

  • res/layout/activity_main.xml
  • TextView txtLong: displays longitude
  • TextView txtLat: displays latitude
<RelativeLayout 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">

    <TextView
        android:id="@+id/txtLong"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:text="Long"
        android:textSize="24dp" />

    <TextView
        android:id="@+id/txtLat"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtLong"
        android:text="Lat"
        android:textSize="24dp" />

</RelativeLayout>

( 3 ) MainActivity.java

  • src/com/hmkcode/android/image/MainActivity.java
  • Beside extending Activity class you need to implement three interfaces
    • GooglePlayServicesClient.ConnectionCallbacks : what you want to do on the connection to the location services & on the dis-connection . You need to implement onConnected() & onDisconnected()
    • GooglePlayServicesClient.OnConnectionFailedListener: what you want to do if the connection failed. You need to implement onConnectionFailed()
    • LocationListener: Called when the location has changed. You need to implement onLocationChanged()
public class MainActivity extends Activity implements 
	GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, 
	LocationListener { ... }
package com.hmkcode.android.location;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

import android.app.Activity;
import android.content.Intent;

import android.location.Location;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements 
    GooglePlayServicesClient.ConnectionCallbacks,
    GooglePlayServicesClient.OnConnectionFailedListener, 
    LocationListener {

    // locations objects
    LocationClient mLocationClient;
    Location mCurrentLocation;
    LocationRequest mLocationRequest;
    
    TextView txtLong,txtLat;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 1. setContnetView
        setContentView(R.layout.activity_main);
        
        // 2. get reference to TextView
        txtLong = (TextView) findViewById(R.id.txtLong);
        txtLat = (TextView) findViewById(R.id.txtLat);

        // 3. create LocationClient
        mLocationClient = new LocationClient(this, this, this);

        // 4. create & set LocationRequest for Location update
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // Set the update interval to 5 seconds
        mLocationRequest.setInterval(1000 * 5);
        // Set the fastest update interval to 1 second
        mLocationRequest.setFastestInterval(1000 * 1);

        
    }
     @Override
        protected void onStart() {
            super.onStart();
            // 1. connect the client.
            mLocationClient.connect();
        }
     @Override
        protected void onStop() {
            super.onStop();
            // 1. disconnecting the client invalidates it.
            mLocationClient.disconnect();
        }
     

    // GooglePlayServicesClient.OnConnectionFailedListener
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
    }

    // GooglePlayServicesClient.ConnectionCallbacks 
    @Override
    public void onConnected(Bundle arg0) {
        
        if(mLocationClient != null)
            mLocationClient.requestLocationUpdates(mLocationRequest,  this);

        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
        
        if(mLocationClient != null){
            // get location
            mCurrentLocation = mLocationClient.getLastLocation();
                try{
                    
                    // set TextView(s) 
                    txtLat.setText(mCurrentLocation.getLatitude()+"");
                    txtLong.setText(mCurrentLocation.getLongitude()+"");
                    
                }catch(NullPointerException npe){
                    
                    Toast.makeText(this, "Failed to Connect", Toast.LENGTH_SHORT).show();

                    // switch on location service intent
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                }
        }

    }
    @Override
    public void onDisconnected() {
        Toast.makeText(this, "Disconnected.", Toast.LENGTH_SHORT).show();
    
    }

    // LocationListener
    @Override
    public void onLocationChanged(Location location) {
        Toast.makeText(this, "Location changed.", Toast.LENGTH_SHORT).show();
        mCurrentLocation = mLocationClient.getLastLocation();
        txtLat.setText(mCurrentLocation.getLatitude()+"");

        txtLong.setText(mCurrentLocation.getLongitude()+"");
    }
    
}

( 4 ) Add Permissions

Android has two location permissions: ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION. The permission you choose controls the accuracy of the current location. If you request only coarse location permission, Location Services obfuscates the returned location to an accuracy that’s roughly equivalent to a city block.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET" />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hmkcode.android.location"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
	
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
	<uses-permission android:name="android.permission.INTERNET" />
	
	
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
        
    </application>

    
</manifest>

Source Code @ GitHub

Leave a Reply