---
title: "Android Location API"  
description: "In this article I am explaining about Android Location API"  
author: "Manoj Pandey"  
published: 2015-03-09  
updated: 2019-09-07  
canonical: https://www.mindstick.com/articles/1636/android-location-api  
category: "android"  
tags: ["android", "google api", "service"]  
reading_time: 4 minutes  

---

# Android Location API

The location APIs make it easy for you to build location-aware [applications](https://www.mindstick.com/articles/12847/how-to-choose-the-right-ethernet-cable-for-industrial-applications), without needing to focus on the details of the underlying location technology. They also let you minimize power consumption by using all of the [capabilities](https://www.mindstick.com/interview/490/explain-the-concepts-and-capabilities-of-assembly-in-dot-net) of the device hardware.This becomes possible with the help of Google Play [services](https://yourviews.mindstick.com/view/82090/advantages-of-using-fuel-delivery-services-at-construction-sites), which facilitates adding location [awareness](https://yourviews.mindstick.com/view/82581/physiotherapy-awareness-and-education) to [your app](https://answers.mindstick.com/qa/33368/how-will-you-design-a-listview-which-downloads-a-lot-of-images-and-displays-in-it-without-getting-your-app-hanged-whats-the-best-possible-way) with automated location tracking, geofencing, and [activity](https://www.mindstick.com/forum/23119/how-to-save-activity-state-in-android) recognition.\

The Location object represents a geographic location which can consist of a latitude, longitude, [timestamp](https://www.mindstick.com/interview/626/what-is-the-physical-storage-length-of-each-of-the-following-db2-data-types-date-time-timestamp), and other information such as bearing, altitude and velocity. There are following important methods which you can use with Location object to get location specific information.

##### This article shows you how to use Location Services in your app to get the

##### current location, get periodic location updates, look up addresses etc.

1. Create an Android project

2. Add [permission](https://answers.mindstick.com/qa/33390/how-to-enable-api-access-in-salesforce-by-permission-set) in [AndroidManifest.xml](https://www.mindstick.com/interview/12768/what-is-the-androidmanifest-xml)

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

\

3. Import project library from C:\Eclipse\adt-bundle-windows-x86_64-20131030\adt-bundle-windows-x86_64-20131030\sdk\extras\google\google_play_services\libproject

4. Add google-play-service-lib as library in [your project](https://www.mindstick.com/forum/156583/best-way-to-link-bootstrap-file-in-your-project)

\
![Android Location API](https://www.mindstick.com/mindstickarticle/cd011d46-caf4-4d7d-87e0-897a0d47bb71/images/15d666bd-9bae-49f6-bfee-0b3fd103df8b.png)\

5. My activity_main.xml file

```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   android:layout_width="fill_parent"   android:layout_height="fill_parent"   android:orientation="vertical" >    <Button android:id="@+id/getLocation"   android:layout_width="fill_parent"   android:layout_height="wrap_content"   android:text="GetLocation"/>    <Button android:id="@+id/disconnect"   android:layout_width="fill_parent"   android:layout_height="wrap_content"   android:text="Disconnect Service"/>     <Button android:id="@+id/connect"   android:layout_width="fill_parent"   android:layout_height="wrap_content"   android:text="Connect Service"/>          <TextView   android:id="@+id/locationLabel"   android:layout_width="wrap_content"   android:layout_height="wrap_content"/>       <TextView   android:id="@+id/addressLabel"   android:layout_width="wrap_content"   android:layout_height="wrap_content"/>    </LinearLayout>
```

6. My AndroidManifest.xml file

```
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.zandroidlocation"    android:versionCode="1"    android:versionName="1.0" >     <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" />  <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" >          <meta-data            android:name="com.google.android.gms.version"          android:value="@integer/google_play_services_version" />        <activity          android:name="com.example.zandroidlocation.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>    </application> </manifest>
```

7. Add following code in MainActivity class

```
package com.example.zandroidlocation; import java.io.IOException;import java.util.List;import java.util.Locale; import com.google.android.gms.common.ConnectionResult;import com.google.android.gms.common.GooglePlayServicesClient;import com.google.android.gms.location.LocationClient; import android.location.Address;import android.location.Geocoder;import android.location.Location;import android.os.AsyncTask;import android.os.Bundle;import android.content.Context;import android.support.v4.app.FragmentActivity;import android.util.Log;import android.view.Menu;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast; public class MainActivity extends FragmentActivity implements           GooglePlayServicesClient.ConnectionCallbacks,           GooglePlayServicesClient.OnConnectionFailedListener {     LocationClient mLocationClient;     private TextView addressLabel;     private TextView locationLabel;     private Button getLocationBtn;     private Button disconnectBtn;     private Button connectBtn;      @Override     protected void onCreate(Bundle savedInstanceState) {           super.onCreate(savedInstanceState);            setContentView(R.layout.activity_main);      locationLabel = (TextView) findViewById(R.id.locationLabel);       addressLabel = (TextView) findViewById(R.id.addressLabel);         getLocationBtn = (Button) findViewById(R.id.getLocation);     getLocationBtn.setOnClickListener(new View.OnClickListener() {                public void onClick(View view) {                     displayCurrentLocation();                }           });           disconnectBtn = (Button) findViewById(R.id.disconnect);     disconnectBtn.setOnClickListener(new View.OnClickListener() {                public void onClick(View view) {                     mLocationClient.disconnect();                    locationLabel.setText("Got disconnected....");                }           });           connectBtn = (Button) findViewById(R.id.connect);        connectBtn.setOnClickListener(new View.OnClickListener() {                public void onClick(View view) {                     mLocationClient.connect();                     locationLabel.setText("Got connected....");                }           });           mLocationClient = new LocationClient(this, this, this);     }      @Override     protected void onStart() {           super.onStart();           // Connect the client.           mLocationClient.connect();           locationLabel.setText("Got connected....");     }      @Override     protected void onStop() {           // Disconnect the client.           mLocationClient.disconnect();           super.onStop();           locationLabel.setText("Got disconnected....");     }          @Override     public void onConnectionFailed(ConnectionResult arg0) {           // TODO Auto-generated method stubToast.makeText(this, "Connection Failure : " + arg0.getErrorCode(),                     Toast.LENGTH_SHORT).show();      }      @Override     public void onConnected(Bundle arg0) {           // TODO Auto-generated method stub    Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();     }      @Override     public void onDisconnected() {           // TODO Auto-generated method stub          Toast.makeText(this, "Disconnected. Please re-connect.",                     Toast.LENGTH_SHORT).show();     }      public void displayCurrentLocation() {           // Get the current location's latitude & longitude     Location currentLocation = mLocationClient.getLastLocation();      String msg = "Current Location: "            + Double.toString(currentLocation.getLatitude()) + ","                + Double.toString(currentLocation.getLongitude());            // Display the current location in the UI           locationLabel.setText(msg);            // To display the current address in the UI           (new GetAddressTask(this)).execute(currentLocation);     }  private class GetAddressTask extends AsyncTask<Location, Void,     String> {           Context mContext;            public GetAddressTask(Context context) {                super();                mContext = context;            }            /*   * When the task finishes, onPostExecute() displays the address.            */           @Override           protected void onPostExecute(String address) {                // Display the current address in the UI                addressLabel.setText(address);           }            @Override           protected String doInBackground(Location... params) {  Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());         // Get the current location from the input parameter list                Location loc = params[0];                // Create a list to contain the result address                List<Address> addresses = null;                try {           addresses = geocoder.getFromLocation(loc.getLatitude(),                                loc.getLongitude(), 10);                } catch (IOException e1) {                                                                            return (e1.toString());                } catch (IllegalArgumentException e2) {                     // Error message to post in the log                     String errorString = "Illegal arguments "                      + Double.toString(loc.getLatitude()) + " , "                            + Double.toString(loc.getLongitude())                                + " passed to address service";                     Log.e("LocationSampleActivity", errorString);                     e2.printStackTrace();                     return errorString;                }                // If the reverse geocode returned an address                if (addresses != null && addresses.size() > 0) {                     // Get the first address                     Address address = addresses.get(0);                     /*      * Format the first line of address (if available), city, and                      * country name.                      */                     String addressText = String.format(                                "%s, %s, %s",                            // If there's a street address, add it                    address.getMaxAddressLineIndex()> 0 ? address                                          .getAddressLine(0) : "",                                // Locality is usually a city                                address.getLocality(),                                // The country of the address                                address.getCountryName());                     // Return the text                     return addressText;                } else {                     return "No address found";                }           }     }// AsyncTask class}
```

Now run your application

![Android Location API](https://www.mindstick.com/mindstickarticle/cd011d46-caf4-4d7d-87e0-897a0d47bb71/images/606a9ae6-3868-4e12-9650-15ac43ec4c82.png)

---

Original Source: https://www.mindstick.com/articles/1636/android-location-api

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
