Android Location API using Google Play Services

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

I am facing an error in the above Json parsing tutorial link of yours . I just imported the same code in android studio and facing some problems.
Could u guys please help me ? I’m facing this error “24576-24715/info.androidhive.jsonparsing
E/ServiceHandler﹕ Couldn’t get any data from the url”. How to overcome
this ? Please help . Thanks in advance

Rahul Arora

Check your internet connection.

Arjun

It is connnected

Rahul Arora

Actually i use same tutorial for ADT and it’s working fine

Arjun

Got it man. Thanks a ton

Arjun

Hello Rahul, could you help me out to get the image from the json at the right corner of each and every list row for the same tutorial or atleast suggest me a tutorial . Thank you

Your tutorials are always great to learn from, so as a Subscriber to your beautiful blog, I request you to please make tutorials on Sync Adapter Framework in Android, where the sync adapter component in the app encapsulates the code for the tasks that transfer data between the device and a server. Thanks 😀 !!

Muhamed

which devices and APIs that works on ?

Francois Lebon-Schneider

Ravi. I’ve been trying to find your email to contact you. We wanted to forward you a press kit for you to see some things http://disa.im is about to release. It’s seriously groundbreaking technology for mobile device power management and message unification.

We’re releasing very soon, but wanted to give the press and some bloggers a sneak peek as well as a secret press webpage web-link which will give you a preview of the new beta version of the app and the new website.

Contact us back by email when you can or personally message me on hangouts.

I am trying to get sim serial number for both the sim card in a dual sim
android mobile but every time I able to get sim serial number for sim
one but for second sim I am getting null value. any suggestion is
appreciated

Hi Ravi, thanks for the code, i have an issue when in “LocationServices.FusedLocationApi.requestLocationUpdates” AS tries to cast third parameter “(com.google.android.gms.location.LocationListener)” anyway it doesn`t work, can you please help me?

tonov

Hi Ravi, thanks for the code, it works fine except when i try to use startLocationUpdates() in “LocationServices.FusedLocationApi.requestLocationUpdates” AS tries to cast third parameter “(com.google.android.gms.location.LocationListener)” anyway when casting it doesn`t work, can you please help me?

i have tested this app but when i click on location updates this message is being shown on the label of get location updates button i have google play services enabled on my device running adnroid 4.2.2 stuck please help me out->: a data connection is required to connect to google playservices,enable google play services

yes everythings is working fine instead of that! my device is also connected to internet actually i am embedding your app to show location on map when , when i click on start location updates that it is giving lat, long values but i have stuck on that ! i m pasting code have a look.
// map_layout.java
package com.example.admin.maps;

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_map_layout, menu);

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement

if (id == R.id.action_settings) {

return true;

}

return super.onOptionsItemSelected(item);

}

}

sajid

using android studio

Arjun

What are the different ways to start an activity in android ?

Сергей Попов

Code download works?

ToddK

Many applications can access this google play services api, and others, is this why when I go to look at battery usage, it shows Google Play Services using more power rather than the applications actually using the service?
p.s. Good tutorial. I liked that it was very detailed in the steps.

Niklas Karlsson

Cool!, do you know any tutorials for saving a small *very small file with backupmanager, or similar?
(Using: …. )

krikor herlopian

first problem is that, this won’t work on certain phones. Second, on this popup GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),

PLAY_SERVICES_RESOLUTION_REQUEST).show(); When I click on get google play services it does nothing on the emulator.Shouldnt it take to some external link

Arjun

Hi Ravi,Please Help, Is application data secured in Android ?

Thang

Thanks Ravi Tamada, your tutorials is great. I have to seen a lots of them, but I wonder why don’t you use Android Studio for simlify import jar/libs?

Hi Ravi, great tutorials you have here, however, i downloaded the source code imported it to eclipse added all the necessary libraries, but when i run it am having some errors; the logcat shows that “Google play store is missing”,”Google Slay services is invalid. Cannot recover.” What could be the problem.

Mitesh Agrawal

Hello Ravi, I tried to run the code but it shows “couldn’t get the location. Make sure location is enabled on the device”. Is it possible to get the location with WIFI/3G/4G connection and gps is turned OFF??

Prathibha Nandini

Hello Mr.Tamada..I have an app based on your old version code..I have an Issue here..I am tracking a device which is at Hyderabad and in my database I got 2 records of Bhopal & delhi..Do you know why this happened..could you help me in tracking the accurate location please…

Richen Yadav

On application launch it gives correct Lat & LOng
but on click START LOCATION UPDATES button
it gives an error — Unfotunatelly,Location Api has Stopped
and application closed

I posted here this message for help no answer at all……what is the purpose…..of disqus……dissapointed….|”|||||||||||||
Hi Ravi, great tutorials you have here, however, i downloaded the source code imported it to eclipse added all the necessary libraries, but when i run it am having some errors; the logcat shows that “Google play store is missing”,”Google Slay services is invalid. Cannot recover.” What could be the problem

Before adding onConnectionCallBacks, everything worked fine.. after adding this and then running app gave this runtime error.
Plzz help urgently

Arun Bisht

I am facing same issue and searching for 2 days but did not find anything .please suggest some solution if you find

gaurav mangal

Hello Hive Team,

we are facing same problem but i don’t have find a better solution fetch location for resolve bugs for Google play jar please provide and suggest me as soon as possible.

al

Hi Ravi, i cann’t download any of ur source after login!!

Ankita Dodia

Hi Ravi,

I saw your Android Location API using Google Play Services example, i try to run this example but i got The import com.google.android.gms.location.LocationServices cannot be resolved error. i m using eclipse and google play service of 17. please reply me how to solve this error.

Arun Bisht

download latest google-play-services lib from sdk manager. you can see com.google.android.gms.location.LocationServices class by extracting new google-play-services.jar file .

Ankita Dodia

Hi Arun, Thanks for Reply, can you please tell me that how to update Google play service because my play service version is 17

I see the app works great when the GPS is on but when GPS is off nothing happened. Is there any way by which we can show user a dialog which would automatically turn GPS ON is GPS is OFF or automatically change GPS setting to HIGH ACCURACY if GPS state is Device only.

I am looking to make it similar to OLACABS android app in which a dialog box comes to ask for user permission if GPS setting is not High accuracy. I think this is standard dialog comes with this API. Can you please help me with this.

Thanks

Thomas kensah, CEO beetlesoft

Yo! Ravi I’ve got to commend you dude. I love your tuts. I can’t seem to find your personal email listed on the site. I’m thom by the way, Web/Mobile apps developer working as an intern at Google Ghana.
I have my own start-up and have handle a few projects with a growing client-list. please get in touch with me on thomaskensah@promustardgh.com. I love your tutorials and would like to partner with you.

Ryan

Excellent Ravi,
This is a useful tutorial for me.

But i can’t download the source code.

Thanks

Kuldeep

Hi am a newbie to Android,

Can you please let me know how I can import the Google play services in android studio ? I really need to learn this for my college project.

I want to keep mobile silent on particular GPS location. Kindly help me ? how can i implement it using your source code??

rajesh

hi thanks for the great tutorial. It works fine. I have one doubt start

i integrate this code and convert this app to save loction in db. it works. but one problem when i click location update button it record location but when i lock screen or minimize the app the location update is now recording to db. How can i continuously get notification of location change even if the app is minimized or screen is locked. please suggest a solution

Vinay Ram

Do you have the same for android studio. if so please share the same

No game No life

In case you dont get output, just add this line in your manifest file and it will work.

Trallallero

Nice tutorial, thanks. But what about if the app needs a constant location update in the background, even if the app is not running ? A Service ? an IntentService ?

Jawe Osk

Did you find the answer?

Trallallero

Yes, I created a boot receiver:

add permission to manifest

and the BootReceiver that extends the BroadcastReceiver:

public class BootReceiver extends BroadcastReceiver

{

@Override

public void onReceive(Context ctx, Intent i)

{

Intent intent = new Intent(ctx, NotificationService.class);

ctx.startService(intent);

}

}

Tested and after reboot, the service is started.

Mohan D Kishore

Hi Trallallero,

Can you please tell me how you created NotificationService for location updates ?

Trallallero

Hi Mohan,

you can get my LocationService.java. It a working service in an app I’ve done and that soon I will publish.

On “updateLoc” method, I store the lat and long and call a db task. There you should handle the result in your own way, of course.

narendra techguy

Location Api has been changed so please update ur tut

Sơn Đinh

Hello Ravi, I tried to run the code but it shows “couldn’t get the location. Make sure location is enabled on the device”.

Sơn Đinh

help me!!!

Nilay Sheth

Hi Ravi,
Very nice tutorial. I have a small question. Suppose I am attaching this demo to a Service, so that I can get a constant location updates from a user whether my app is running or closed, then will google block my app in future for violating any of its policy ?

Ulhas Patil

Hey Ravi,
I am searching for getting location Offline without Internet, WiFi and GPS, using Network_Provider but my code is work fine below 4.4 but not working on Lollipop.
Do you know any solution for that ? I did lot of search about it, but nothing found any solution for that. Please reply me.

Mustansar

Hi, How you are getting location in offline without internet, wifi and gps?

could you please share menu->main.xml for this. i am getting error.Please send this to my emil parida.amiya@gmail.com

Johnny boy

Works great – but when Location is set to ‘Device Only’ it does not work. no GPS?

Grusp

So awesome thanks Mr. Ravi!

giupardeb

Thankyou very much Mr. Ravi !
But, I have a problem, why the onLocationChanged method give me a error: method does not override or implement a method from a supertype. Why?

Rickenbacker

Hello and thanks for the useful tutorial. I have a question about the version of Android where it first appeared this new feature. Since 4.2?
Cause my teacher talked about some change since version 5 (lollipop) but all the documentation doesn’t mention this fact. Any new change since Android 5? Obviously talking about the location api only. Thanks!

Zem The Handsome

Appreciate your Tutorials Ravi Tamada, but I guess we should start using Android Studio, so that android studio users can download and test it right away.

Niranjan Sridhara

Hi Ravi,
I am not getting the the location updates when my application goes to background or mobile gets locked… please help me out…

Getting this error while implementing the above code,
What’s happening?

manoj kumar

This is very nice Example , i tried this code with background Servcies Tracking its not working Properly. can you add sample code for Finding the GPS location with New Google API UsIng Background Service. even Appilication is Closed ,it should get location and Send to server periodically.

Sagar Thakarar

i done the import process as u said above for Google play Service.
when i do import it to use in peoject it gives error like this :

Error retrieving parent for item: No resource found that matches the given name ‘@android:style/Theme.Holo.Light.DialogWhenLarge.NoActionBar
in google-play-services_lib/res/values-v11/appinvite_style.xml

and

Error retrieving parent for item: No resource found that matches the
given name ‘@android:style/Theme.Material.Light.DialogWhenLarge.NoActionBar in google-play-services_lib/res/values-v21/appinvite_style.xml

Hi thanks for the great example, do you know why i’m getting this error, GoogleApiClient is not connected yet ?

jimi

Did you get a solution to this problem?

Rak

Because you are missing the mGoogleApiClient.connect() in the onConnected method.

Jazmin G

Hi, thanks for the great example, but I have some questions about it, when I cliked the button Start Location Update, all function perfetc, but when I rotary my phone screen, the button automacatilly is stop, hava any method to fix it?

Swati Agarwal

Ravi , thanks a lot for sharing your knowledge. I have been following you since long ..Seriously you offer great help to everyone , Continue doing it, Thanks again

C. Chen

Thanks for great examples. I am having a error regarding LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); method can’t be resolved. Can anyone help how to solve this one? Thank you very much.

AH

check your LocationListener that you implement to the activity, make sure it imported from com.google.android.gms.location.LocationListener, not this one -> android.location.LocationListener

Derek

Hey guys! A Christian American here. I can’t wait to try this example in Android Studio 2.0 with API 23 and Android 6.0 (Marshmallow). I have been having difficulty finding good tutorials online for finding a user’s GPS location. Oddly, there is barely anything that actually works….and not to mention that I am a completely new beginner (as of 1 month ago).

Hi,
can you tell that why are we calling
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
in displayLocationChanged() when we receive a Location object in onLocationChanged(Location location) and assign mLastLocation=location.
is called on requesting location updates.
Can the object received by onLocationChanged be Null or have some garbage value which does not have a lat,long

kshitiz

how to achieve @integer/google_play_services_version in meta-data as i am implementing the code on android studio

nitu

Hi Ravi,
Thanking you for simple code ..I am not getting the location in emulator and there were no errors in studio also… Can you help me…

Space Fish

Not sure if this is really up to date anymore. I’m having lots of problems with the new permission checking at runtime. Is there any easy way to adapt this for the new permission method?

khalid nabi

sir i dont have google play service under extras in android sdk manager.wt will i do..please reply must

Mahesh Mohan

in kitkat its working i am getting location with out tern on location. but in lollipop not working

Harish

Hi Ravi,

I tried the above application in android studio. I am getting an exception . I am running on my mobile with android version 6.0.
Exception details..