Android Location Based Services

Android Location Based Services

Android location based services APIs make it easy that you can build location-aware apps, without having to concentrate on the facts of the root location technology.

It becomes possible with the aid of Google Play services, which helps adding location recognition to your software with robotic location monitoring, geo-fencing, and activity acknowledgement.

android location based services

You are exhibited by this article how to use Android Location Based Services in your APP to get the existing location, get regular location updates, research addresses etc

The Android Location Object

The Android Location subject/object symbolizes a geographic location which can contain a latitude, longitude, time stamp, and other information for example bearing, velocity and altitude. You will find following important methods used with Location object to get location specific information:

Android Location Based Services Methods

  1. Float disatanceTo(Location dest)
  2. float getAccuracy()
  3. double getAltitude()
  4. float getBearing()
  5. double getLatitude()
  6. double getLongitude()
  7. float getSpeed()
  8. boolean hasAccuracy()
  9. boolean hasAltitude()
  10. boolean hasBearing()
  11. boolean hasSpeed()
  12. void reset()
  13. void setAccuracy(float accuracy)
  14. void setAltitude(double altitude)
  15. void setBearing(float bearing)
  16. void setLatitude(double latitude)
  17. void setLongitude(double longitude)
  18. void setSpeed(float speed)
  19. String toString()

Get the Current Location

To get the existing android location, create a spot customer which is LocationClient subject, hook up it to Android Location Based Services using connect() method, and then call its getLastLocation() method. This technique returns the newest location by means of Location object which has latitude and longitude coordinates and other information as described above. To obtain android  location based services efficiency in your activity, you shall have to use two interfaces

  • Android ConnectionCallbacks
  • Android OnConnectionFailedListener

These interfaces provide pursuing important callback methods, that you need to put into action in your activity class

Callback methods and Description

abstract void onConnected(Bundle connectionHint)

This callback method is named when android location based services is linked to the positioning client effectively. You use connect() solution to hook up to the positioning client.

abstract void onDisconnected()

This callback method is named when your user is disconnected. You use disconnect() solution to disconnect from the positioning user.

abstract void onConnectionFailed(ConnectionResult end result)

This callback method is named when there is one attaching your client to the service.


You need to create the positioning customer in onCreate() approach to your activity class, then hook up it in onStart(), so that Android Location Based Services retains the existing location while your activity is completely visible. You must disconnect your client in onStop() method, so that whenever your software is not obvious, Android Location Based Services is not keeping the existing location. This can help in saving battery up-to a sizable extent.

Get the Updated Android Location

If you’re willing to own location updates, then aside from previously listed interfaces, you’ll need to use LocationListener user interface as well. This interface provide following callback method, that you need to implement in your activity class –

Callback Method & Description

abstract void onLocationChanged(Location location)

This method can be used for obtaining notifications from the LocationClient when the positioning/location has changed.

Android Location Quality of Service

The LocationRequest thing can be used to request an excellent of service (QoS) for location revisions from the LocationClient. You will find pursuing useful setter methods used to take care of QoS. You can find similar getter methods available which you are able to check in Android OS official documentation.

Method & Description

setExpirationDuration(long millis)

Set the length of this need, in milliseconds.

setExpirationTime(long millis)

Set the demand expiration time, in millisecond since shoe.

setFastestInterval(long millis)

Set the most effective interval for location updates explicitly, in milliseconds.

setInterval(long millis)

Set the required interval for productive location posts, in milliseconds.

setNumUpdates(int numUpdates)

Arranged the amount of location revisions.

setPriority(int concern)

Set the main concern of the request.

For example now, if the application wants high correctness location it will create a location request with setPriority(int) establish to Top priority_HIGH_ACCURACY and setInterval(long) to 5 moments. You can even use bigger period and/or other priorities like Concern_LOW_POWER for to question “city” level exactness or Top priority_BALANCED_POWER_ACCURACY for “block” level reliability.

Activities should firmly consider taking away all location request when entering the backdrop (for example at onPause()), or at least swap the get to a more substantial period and lower quality to save lots of power consumption.


Displaying an Android  Location Address

Once if  you’ve Android Location object, you may use Geocoder.getFromLocation() solution to get an address for confirmed latitude and longitude. This technique is synchronous, and could take a very long time to do its work, and that means you should call the technique from the doInBackground() approach to an AsyncTask school.

The AsyncTask must be subclassed to be utilized and the subclass will override doInBackground(Params…) solution to perform an activity in the backdrop and onPostExecute(Effect) method is invoked on the UI thread following the background computation coatings and at that time to display the effect. There is yet another important method available in AyncTask which is execute(Params… params), this technique executes the task with the given parameters.

Check pursuing example to own better understanding how we use AynchTask in virtually any Android program to get work done in the backdrop without interfering main process.

How To User Android Location Based Services

Following android location based services example teaches you in functional how to to work with Android Location Based Services in your software to get the existing location and its own comparative addresses etc.

To test out this android location based services example, you shall need real Mobile device prepared with latest Google android Operating-system, otherwise you will have to struggle with emulator which may well not work.

Install the Google Play Services SDK

Before you check out have location support in your Android os Applications, you will need to set-up Google Play Services SDK using pursuing easy steps –

Steps     Description

1-Launch Android Studio room IDE

From Android Studio room choose  >project structure >dependencies > Click on + button to add dependencies

you’ll get choose collection dependencies dialog window

2 -Search for os.gms:play-services:6.5.87 or more version collection. its rely upon which android version is using with.

3-Select the google play services and press apply button as shown below image

How To Create Android Application

  1. You use Android studio IDE to make an Android software and name it as Androdevelopment under a offer com.example.androdevelopmnet. While creating this job, be sure to Goal SDK and Compile With at the latest version of Google android SDK to make use of higher degrees/levels of APIs.
  2. Add Google Play Service catalogue in assembling your project by following easy steps given below.
  3. Modify src/  and add required code as shown below to care for getting current location and its own equivalent address.
  4. Modify structure XML res/design/activity_main.xml to include all GUI components such as three keys and two content material views showing location/address.
  5. Modify res/worth/strings.xml to specify required regular values
  6. Modify AndroidManifest.xml as shown below
  7. Run the application form to launch Android os emulator and validate the consequence of the changes done in the application form.

Let’s add Google Play Service reference point in the project.Click on data file > project structure > dependencies > and choose + and then search google play services which shows Select ok button. it’ll close the choose dependencies glass windows. you must be close project structure by clicking apply button

android location based services

Above image is exhibiting the consequence of adding google play services to task. after add google play services to project. It ought to be as follows

android location based services

Following is the content of the modified main activity file src/com.example.Androdevelopment/

package com.example.Androdevelopment;

import java.util.List;
import java.util.Locale;


import android.content.Context;

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;

import android.os.AsyncTask;
import android.os.Bundle;

import android.util.Log;
import android.view.View;

import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements
   LocationClient mLocationClient;
   private TextView addressLabel;
   private TextView locationLabel;
   private Button getLocationBtn;
   private Button disconnectBtn;
   private Button connectBtn;

   protected void onCreate(Bundle savedInstanceState) {
      locationLabel = (TextView) findViewById(;
      addressLabel = (TextView) findViewById(;
      getLocationBtn = (Button) findViewById(;
      getLocationBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
      disconnectBtn = (Button) findViewById(;
      disconnectBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            locationLabel.setText("Got disconnected....");
      connectBtn = (Button) findViewById(;
      connectBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            locationLabel.setText("Got connected....");
      // Create the LocationRequest object
      mLocationClient = new LocationClient(this, this, this);
   protected void onStart() {
      // Connect the client.
      locationLabel.setText("Got connected....");
   protected void onStop() {
      // Disconnect the client.
      locationLabel.setText("Got disconnected....");
   public void onConnected(Bundle dataBundle) {
      // Display the connection status
      Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
   public void onDisconnected() {
      // Display the connection status
      Toast.makeText(this, "Disconnected. Please re-connect.",Toast.LENGTH_SHORT).show();
   public void onConnectionFailed(ConnectionResult connectionResult) {
      // Display the error code on failure
      Toast.makeText(this, "Connection Failure : " + connectionResult.getErrorCode(),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()) + "," +
      // Display the current location in the UI
      // To display the current address in the UI
      (new GetAddressTask(this)).execute(currentLocation);
   * Following is a subclass of AsyncTask which has been used to get
   * address corresponding to the given latitude & longitude.
   private class GetAddressTask extends AsyncTask<Location, Void, String>{
      Context mContext;
      public GetAddressTask(Context context) {
         mContext = context;
      * When the task finishes, onPostExecute() displays the address.
      protected void onPostExecute(String address) {
         // Display the current address in the UI
      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
         <Address> addresses = null;
         try {
            addresses = geocoder.getFromLocation(loc.getLatitude(),loc.getLongitude(), 1);
         catch (IOException e1) {
            Log.e("LocationSampleActivity",IO Exception in getFromLocation());
            return ("IO Exception trying to get address");
         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);
            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
            // The country of the address
            // Return the text
            return addressText;
         else {
            return "No address found";
   }// AsyncTask class


Following will be the content of res/layout/activity_main.xml file −

<LinearLayout xmlns:android=""
   android:orientation="vertical" >
   <TextView android:id="@+id/textView1"
      android:text="Location Example"
      android:textSize="30dp" />

   <TextView android:id="@+id/textView2"
      android:text="Andro Development "
      android:layout_alignEnd="@+id/imageButton" />

   <ImageButton android:layout_width="wrap_content"
      android:layout_centerHorizontal="true" />

   <Button android:id="@+id/getLocation"
   <Button android:id="@+id/disconnect"
   <Button android:id="@+id/connect"



Following will be the content of res/values/strings.xml to define two new constants:

<?xml version="1.0" encoding="utf-8"?>
   <string name="app_name">Andro development</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="get_location">Get Location</string>
   <string name="disconnect">Disconnect Service</string>
   <string name="connect">Connect Service</string>

Following is the default content of AndroidManifest.xml 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
   android:versionName="1.0" >
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
      android:theme="@style/AppTheme" >
         android:label="@string/app_name" >
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />

How about we attempt to run our Androdevelopment application we simply developed. I accept you had made your AVD while doing android environment setup. To run the application from Android studio, open one of your project activity file and snap  Android Studio Run Icon    from the tool bar. Android Studio installs the application on your AVD and begins it and if all is well with your set-up and application, it will show taking after Emulator window

android location based services

Now to see location go for Get Location Button that will screen location information the following


You can test by disconnecting location consumer using Disconnect Service and then attaching it by using Connect Service button. You can even enhance to get location revise as discussed above and in Google android Official documentation.