articles

Home / DeveloperSection / Articles / Android Location API

Android Location API

Manoj Pandey3812 09-Mar-2015

The location APIs make it easy for you to build location-aware 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 of the device hardware.This becomes possible with the help of Google Play services, which facilitates adding location awareness to your app with automated location tracking, geofencing, and activity recognition.

The Location object represents a geographic location which can consist of a latitude, longitude, 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 in AndroidManifest.xml

 

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

   <uses-permissionandroid: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   


 Android Location API

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

 


Updated 07-Sep-2019

Leave Comment

Comments

Liked By