Android GPS, Location Manager Tutorial

One of the major features of android framework is location API. You can see, the location module widely used in lot of apps those provides services like food ordering, transportation, health tracking, social networking and lot more. The location module is part of Google Play Services and in the same module geofencing and activity recognition are included.

In this article we are going to cover the basics of location API with an example app.

1. Introduction

Earlier, getting location is very easy with couple of API calls. But to provide more accurate locations and optimizing the battery usage, Android introduced set APIs that should be combined to get the best results from the location API. We will be using Fused Location API that combines signals from GPS, Wi-Fi, and cell networks, as well as accelerometer, gyroscope, magnetometer and other sensors to provide more accurate results.

1.1 Location Permissions

There are two permissions available to request location. The accuracy of the location is determined by the kind of permission requested and priority level.

ACCESS_COARSE_LOCATION: Gives location approximately equivalent to a city block.

ACCESS_FINE_LOCATION: Gives precise location, sometimes in few meters or feet when combined with High Priority accuracy.

1.2 Receiving Location Updates

getLastLocation(): Returns the recent available location. When location is not available, it returns null.

Location Settings: In order to get the location, proper settings has to enabled in the device such as GPS or Wifi. Instead of requesting the user to enable them separately, you can use Settings Client to check whether proper settings are enabled or not. If enabled, you can proceed with location updates or user will be shown a dialog to turn on the required hardware as shown below.

Update Interval: This interval defines the rate in milliseconds at which your app prefers the location updates. Your app can receive updates lesser or higher than this rate if other apps requested location updates higher than your value. Let’s say your app requests updates every 10secs, if other app is requesting updates at 5secs, your app might receives the same updates ignoring the 10sec value.

Fastest Update Interval: This is the rate at which your app can handle the location updates. Without this value, you can see inconsistent user experience if your app can’t handle frequent location updates.

Priority: The accuracy of the location depends on the source of the hardware used. To define this, Priority has to be mentioned while requesting the location. The priority can be BALANCED, HIGH, LOW OR NO_POWER.

1.3 Example App

Here is the demo app we are going to implement in this article. The app receives the location updates when it is opened and updates will be stopped when app goes to background.

Let’s jump to coding part by creating a new project in Android Studio.

2. Creating New Project

1. Create a new project in Android Studio from File ⇒ New Project and select Basic Activity from templates.

5. Open the layout file of main activity activity_main.xml and add the below code. In this layout, few Buttons and TextViews are defined to toggle the location updates and display location information.

6. Open MainActivity.java and add the below code. Initially the code might look heavy but with couple of observations you can understand it easily.

First we initialize all the location related clients such as FusedLocationProviderClient, LocationRequest, LocationSettingsRequest, LocationCallback and SettingsClient in onCreate() method.

While initializing, we define the interval setInterval(), fastest interval setFastestInterval() and priority setPriority() on location request.

Dexter is used to request the location permission before performing any location related operations.

startLocationUpdates() requests for location updates. First, it checks whether the location settings are eanbled and once satisfied, the updates will be requested. Here SettingsClient is used to check for settings configuration.

The location updates will be received in LocationCallback and proper UI action is taken place. If you really want to the location only once, you can call stopLocationUpdates() method immediately after receiving the first location update.

The location updates are paused and resume in onPause() and onResume() method to save the batter power.

Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info

Thanks for the tutorial but it’s outdated.
I’ve tried several methods but none of them works, including this one.
As far as I know, the problem is that the methods of getting location has changed a lot.
Can you post the updated method please?

the problem for get a value of 0.0 lat long , the permission is not allowed for gps , you can check that from setting phone, you will see ” no permissions allowed “

RAHUL MAURYA

give ur app permission for location manually in setting

Karthikeyan

I am using your above code to get location. my problem is, prompts the user to enable GPS if it’s not on and I have used AlertDialog for this purpose. After I enable the GPS from settings and come back to my app by pressing back button, the toast message display 0.00,0.00. Although If I have my GPS on before running the app, the app properly displays my location. I want to know to which method to use for this refresh user location after enabling GPS purpose. Any relevant article would really help.

Hi i am using your tutorial it is working in MI phones but surprisingly it does not work in Samsung On8 ..
it getting null
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastLocation ==null

could you please help me here.

Im Ug

I have a question. I have many GPS modules that I can connect to my PC via FT232 or CP2102. Can I use them with an Android emulator together with this GPS API? If yes, how?

신종호 (ABCDEFG)

I created the app as above code. However, the current coordinates are received as latitude: 0.0 longitude: 0.0.
What is the problem?

You need to open LogCat in Android Studio when the app is crashed to see the errors.

Gunjan Sharma

Hi
When i run the application it is showing lat and long both are 0 ….
please help me to solve this issue

hala

Please, I have the same problem
How could you solve it??

DirectionalAudio DirectionalAu

I have to implement onRequestPermissionsResult() for this GPSTRACKER SERVICE how to do that?

inderjit singh

i need current location of user with the help of GPS provider.

Currently i’m getting GPS location, but in some devices i’m not getting location.

I also tried last known location and network location, but they are not accurate.

So please help by providing better solution.

Ashok Sennan

i want to get the exact latitude and longitude of user..is it posible in gpstracking??

Michael Lukin

Yes, there is a section “Getting Latitude and Longitude” in this article

shivani

hey hi can you help me out with google map v2 error ??
Well my issue is : I can see the route with markers when i debug the code on my device but can see blank map when i run the same code on the same device

Smita Sonavane

Even though location mode is with high accuracy, sometimes code returns null location value continuously what should I do at that time?

hi your tutorial is very helpful
i want to ask that i want to save my current latitude and longitude in database automatically that is when someone login to my application his/her current latitude and longitude should be save automatically in database and then i want it to be show on google map can u plz help me
Thanks in advance

Manuel

Hey, thank you for the helpful tutorial. While implementing a similar location management I got to the question, if there is a special reason, that you decided to use the network provider first, and only if no location is found by that, the location is determined by gps?

Nitul Barman

thank you for the tutorial.. but it only shows latitude and longitude with wifi connection . please help

TAGNE TOKAM Cedrick Gaetan

Hi,

TAGNE TOKAM Cedrick Gaetan

Please I always have 0.0 as longitude and as latitude can you please help me?
thanks

alex

check your permissions

jayesh

Hello sir,
this demo completely work in other mobile but in moto and Samsung i always get 0 value.
i have already code to run time permission and also check permission in setting all is done but i get o lat long
please give me reply what can i do??