In my previous post about Android GPS, Location Manager, I explained how to get device location (latitude & longitude) using the older android APIs. Now google introduced new way of getting device location using the Google Play Services.

A newer api called FusedLocationApi was introduced which connects with GoogleApiClient and gives us the best location available.

So let’s start this by creating a simple app.

android location api using google play services

1. Downloading & Importing Google Play Services

As this app needs Google Play Services, we need to setup the play services first. If you have the play services installed already, update them to latest version using Android SDK Manager.

1. Open Android SDK Manager and install or update the play services under Extras section.

android sdk manager installing play services

2. In Eclipse goto File ⇒ Import ⇒ Android ⇒ Existing Android Code Into Workspace

3. Click on Browse and select Google Play Services project from your android sdk folder. You can locate play services library project from
android-sdk-windows\extras\google\google_play_services\libproject\google-play-services_lib

4. And check Copy projects into workspace option as shown in the below image, which places a copy of play services in eclipse workspace.

google api console creating new client id

2. Creating Android Project

Once the play services are downloaded and imported into eclipse workspace, we can start building a simple app with the location services integrated.

1. In Eclipse create a new android project by navigating to File ⇒ New ⇒ Android Application Project and fill out all the required details.

I gave my project name as Location API and package name as info.androidhive.locationapi

2. Add the Google Play Services project as a library to our project. Right click on the project and select properties. In the properties window, on left side select Android. On the right, you can see a Add button under library section. Click it and select google play services library which we imported previously

android google play services library project
android google play services library project
android google play services library project

3. Download this marker.png and paste it in your project’s src ⇒ res ⇒ drawable-ldpi folder. (Please note that this is a white color png image, it might not be visible in your browser window)

4. Open strings.xml located under res ⇒ values and add below string values.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Location API</string>
    <string name="lbl_you_are_at">YOU ARE AT</string>
    <string name="btn_get_location">GET MY LOCATION</string>
    <string name="btn_start_location_updates">START LOCATION UPDATES</string>
    <string name="btn_stop_location_updates">STOP LOCATION UPDATES</string>

</resources>

5. Open colors.xml located under res ⇒ values and add below color values. If you don’t see colors.xml, create a new file with the name.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <color name="view_bg">#b20e0f</color>
    <color name="white">#ffffff</color>
    <color name="btn_bg">#3e4a56</color>

</resources>

6. Open AndroidManifest.xml and add ACCESS_FINE_LOCATION permission. You also need to add below meta-data for google play services version.

<meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

After doing required changes, your AndroidManifest.xml should look like below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.locationapi"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

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

    <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="info.androidhive.locationapi.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

7. Now we’ll quickly create a simple layout for our app. Open the layout file of your main activity (activity_main.xml) and add below code. This layout contains a TextView to display the location and two buttons (one is to get location and other is to toggle periodic location updates).

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/view_bg"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <ImageView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginTop="60dp"
        android:src="@drawable/marker" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="@string/lbl_you_are_at"
        android:textColor="@color/white"
        android:textSize="25dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/lblLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:padding="15dp"
        android:textColor="@color/white"
        android:textSize="16dp" />

    <Button
        android:id="@+id/btnShowLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:background="@color/btn_bg"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:text="@string/btn_get_location"
        android:textColor="@color/white" />

    <Button
        android:id="@+id/btnLocationUpdates"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:background="@color/btn_bg"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:text="@string/btn_start_location_updates"
        android:textColor="@color/white" />

</LinearLayout>

8. Now we’ll start adding the code related to location api. Open your main activity MainActivity.java and implement the class from ConnectionCallbacks, OnConnectionFailedListener.

public class MainActivity1 extends Activity implements ConnectionCallbacks,
		OnConnectionFailedListener {

}

In brief, you need to do below changes in your activity to get the user’s current location.

> First check for availability of Google Play Services by calling checkPlayServices() in onResume()

> Once play services are available on the device, build the GoogleApiClient by calling buildGoogleApiClient() method.

> Connect to google api client by calling mGoogleApiClient.connect() in onStart() method. By calling this, onConnectionFailed(), onConnected() and onConnectionSuspended() will be triggered depending upon the connection status.

> Once google api is successfully connected, displayLocation() should be called in onConnected() method to get the current location.

Add the below code to your main activity and run the project. Make sure that the wifi and location is enabled on your device before you test.

package info.androidhive.locationapi;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import android.app.Activity;
import android.location.Location;
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 MainActivity1 extends Activity implements ConnectionCallbacks,
		OnConnectionFailedListener {
	// LogCat tag
	private static final String TAG = MainActivity.class.getSimpleName();

	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

	private Location mLastLocation;

	// Google client to interact with Google API
	private GoogleApiClient mGoogleApiClient;

	// boolean flag to toggle periodic location updates
	private boolean mRequestingLocationUpdates = false;

	private LocationRequest mLocationRequest;

	// Location updates intervals in sec
	private static int UPDATE_INTERVAL = 10000; // 10 sec
	private static int FATEST_INTERVAL = 5000; // 5 sec
	private static int DISPLACEMENT = 10; // 10 meters

	// UI elements
	private TextView lblLocation;
	private Button btnShowLocation, btnStartLocationUpdates;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		lblLocation = (TextView) findViewById(R.id.lblLocation);
		btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
		btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);

		// First we need to check availability of play services
		if (checkPlayServices()) {

			// Building the GoogleApi client
			buildGoogleApiClient();
		}

		// Show location button click listener
		btnShowLocation.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				displayLocation();
			}
		});
	}

	/**
	 * Method to display the location on UI
	 * */
	private void displayLocation() {

		mLastLocation = LocationServices.FusedLocationApi
				.getLastLocation(mGoogleApiClient);

		if (mLastLocation != null) {
			double latitude = mLastLocation.getLatitude();
			double longitude = mLastLocation.getLongitude();

			lblLocation.setText(latitude + ", " + longitude);

		} else {

			lblLocation
					.setText("(Couldn't get the location. Make sure location is enabled on the device)");
		}
	}

	/**
	 * Creating google api client object
	 * */
	protected synchronized void buildGoogleApiClient() {
		mGoogleApiClient = new GoogleApiClient.Builder(this)
				.addConnectionCallbacks(this)
				.addOnConnectionFailedListener(this)
				.addApi(LocationServices.API).build();
	}

	/**
	 * Method to verify google play services on the device
	 * */
	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(this);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, this,
						PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} else {
				Toast.makeText(getApplicationContext(),
						"This device is not supported.", Toast.LENGTH_LONG)
						.show();
				finish();
			}
			return false;
		}
		return true;
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (mGoogleApiClient != null) {
			mGoogleApiClient.connect();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		checkPlayServices();
	}

	/**
	 * Google api callback methods
	 */
	@Override
	public void onConnectionFailed(ConnectionResult result) {
		Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
				+ result.getErrorCode());
	}

	@Override
	public void onConnected(Bundle arg0) {

		// Once connected with google api, get the location
		displayLocation();
	}

	@Override
	public void onConnectionSuspended(int arg0) {
		mGoogleApiClient.connect();
	}
}

android location api using google play services

Receiving Location Updates

9. In certain scenarios, your app might needs location updates periodically. Let’s say you are building a direction app where user needs to be get updated whenever location is changed. In that case you need to request for location updates. Doing the below changes, you will get the new location wherever location is changed.

> Implement the activity from LocationListener which adds onLocationChanged() method.

> Create LocationRequest object by calling createLocationRequest() method in onCreate() method upon checking the play services availability.

> Add togglePeriodicLocationUpdates() method which toggles listening to location updates.

> Start the location updates by calling startLocationUpdates() in onConnected() and onResume() methods.

> Stop the location updates by calling stopLocationUpdates() in onStop().

> startLocationUpdates() and stopLocationUpdates() methods are used to start/stop the location updates.

> onLocationChanged() method will be triggered whenever the location is changed. Calling displayLocation() inside onLocationChanged will display new location data on the UI.

public class MainActivity extends Activity implements ConnectionCallbacks,
		OnConnectionFailedListener, LocationListener {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// First we need to check availability of play services
		if (checkPlayServices()) {

			createLocationRequest();
		}

		// Toggling the periodic location updates
		btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				togglePeriodicLocationUpdates();
			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();

		// Resuming the periodic location updates
		if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
			startLocationUpdates();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		stopLocationUpdates();
	}

	/**
	 * Method to toggle periodic location updates
	 * */
	private void togglePeriodicLocationUpdates() {
		if (!mRequestingLocationUpdates) {
			// Changing the button text
			btnStartLocationUpdates
					.setText(getString(R.string.btn_stop_location_updates));

			mRequestingLocationUpdates = true;

			// Starting the location updates
			startLocationUpdates();

			Log.d(TAG, "Periodic location updates started!");

		} else {
			// Changing the button text
			btnStartLocationUpdates
					.setText(getString(R.string.btn_start_location_updates));

			mRequestingLocationUpdates = false;

			// Stopping the location updates
			stopLocationUpdates();

			Log.d(TAG, "Periodic location updates stopped!");
		}
	}

	/**
	 * Creating location request object
	 * */
	protected void createLocationRequest() {
		mLocationRequest = new LocationRequest();
		mLocationRequest.setInterval(UPDATE_INTERVAL);
		mLocationRequest.setFastestInterval(FATEST_INTERVAL);
		mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
		mLocationRequest.setSmallestDisplacement(DISPLACEMENT); // 10 meters
	}

	/**
	 * Starting the location updates
	 * */
	protected void startLocationUpdates() {

		LocationServices.FusedLocationApi.requestLocationUpdates(
				mGoogleApiClient, mLocationRequest, this);

	}

	/**
	 * Stopping location updates
	 */
	protected void stopLocationUpdates() {
		LocationServices.FusedLocationApi.removeLocationUpdates(
				mGoogleApiClient, this);
	}

	@Override
	public void onConnected(Bundle arg0) {

		// Once connected with google api, get the location
		displayLocation();

		if (mRequestingLocationUpdates) {
			startLocationUpdates();
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		// Assign the new location
		mLastLocation = location;

		Toast.makeText(getApplicationContext(), "Location changed!",
				Toast.LENGTH_SHORT).show();

		// Displaying the new location on UI
		displayLocation();
	}

}

After doing all the above changes, run and test the app. If your app is not getting location, follow below steps to debug the app.

android location api using google play services

3. Testing the App

Below are the few key points should be kept in mind while testing the app.

> Your device should have internet connection (Wifi or mobile 3G).

> Location service should be enabled. Go to Settings => Location => Turn On.

> When you run the app, if you are not able to get the location even though you have done above two steps, open any of google’s location apps (maps) and come back to our app or just tap on START LOCATION UPDATES.

> If you are testing the periodic location updates, go out and take a short walk (few steps). You should see the locationChanged method calling by giving latest location coordinates.

Complete Code:

Below is the complete code of MainActivity.java

package info.androidhive.locationapi;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends Activity implements ConnectionCallbacks,
		OnConnectionFailedListener, LocationListener {

	// LogCat tag
	private static final String TAG = MainActivity.class.getSimpleName();

	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

	private Location mLastLocation;

	// Google client to interact with Google API
	private GoogleApiClient mGoogleApiClient;

	// boolean flag to toggle periodic location updates
	private boolean mRequestingLocationUpdates = false;

	private LocationRequest mLocationRequest;

	// Location updates intervals in sec
	private static int UPDATE_INTERVAL = 10000; // 10 sec
	private static int FATEST_INTERVAL = 5000; // 5 sec
	private static int DISPLACEMENT = 10; // 10 meters

	// UI elements
	private TextView lblLocation;
	private Button btnShowLocation, btnStartLocationUpdates;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		lblLocation = (TextView) findViewById(R.id.lblLocation);
		btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
		btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);

		// First we need to check availability of play services
		if (checkPlayServices()) {

			// Building the GoogleApi client
			buildGoogleApiClient();

			createLocationRequest();
		}

		// Show location button click listener
		btnShowLocation.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				displayLocation();
			}
		});

		// Toggling the periodic location updates
		btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				togglePeriodicLocationUpdates();
			}
		});

	}

	@Override
	protected void onStart() {
		super.onStart();
		if (mGoogleApiClient != null) {
			mGoogleApiClient.connect();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		checkPlayServices();

		// Resuming the periodic location updates
		if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
			startLocationUpdates();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mGoogleApiClient.isConnected()) {
			mGoogleApiClient.disconnect();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		stopLocationUpdates();
	}

	/**
	 * Method to display the location on UI
	 * */
	private void displayLocation() {

		mLastLocation = LocationServices.FusedLocationApi
				.getLastLocation(mGoogleApiClient);

		if (mLastLocation != null) {
			double latitude = mLastLocation.getLatitude();
			double longitude = mLastLocation.getLongitude();

			lblLocation.setText(latitude + ", " + longitude);

		} else {

			lblLocation
					.setText("(Couldn't get the location. Make sure location is enabled on the device)");
		}
	}

	/**
	 * Method to toggle periodic location updates
	 * */
	private void togglePeriodicLocationUpdates() {
		if (!mRequestingLocationUpdates) {
			// Changing the button text
			btnStartLocationUpdates
					.setText(getString(R.string.btn_stop_location_updates));

			mRequestingLocationUpdates = true;

			// Starting the location updates
			startLocationUpdates();

			Log.d(TAG, "Periodic location updates started!");

		} else {
			// Changing the button text
			btnStartLocationUpdates
					.setText(getString(R.string.btn_start_location_updates));

			mRequestingLocationUpdates = false;

			// Stopping the location updates
			stopLocationUpdates();

			Log.d(TAG, "Periodic location updates stopped!");
		}
	}

	/**
	 * Creating google api client object
	 * */
	protected synchronized void buildGoogleApiClient() {
		mGoogleApiClient = new GoogleApiClient.Builder(this)
				.addConnectionCallbacks(this)
				.addOnConnectionFailedListener(this)
				.addApi(LocationServices.API).build();
	}

	/**
	 * Creating location request object
	 * */
	protected void createLocationRequest() {
		mLocationRequest = new LocationRequest();
		mLocationRequest.setInterval(UPDATE_INTERVAL);
		mLocationRequest.setFastestInterval(FATEST_INTERVAL);
		mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
		mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
	}

	/**
	 * Method to verify google play services on the device
	 * */
	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(this);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, this,
						PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} else {
				Toast.makeText(getApplicationContext(),
						"This device is not supported.", Toast.LENGTH_LONG)
						.show();
				finish();
			}
			return false;
		}
		return true;
	}

	/**
	 * Starting the location updates
	 * */
	protected void startLocationUpdates() {

		LocationServices.FusedLocationApi.requestLocationUpdates(
				mGoogleApiClient, mLocationRequest, this);

	}

	/**
	 * Stopping location updates
	 */
	protected void stopLocationUpdates() {
		LocationServices.FusedLocationApi.removeLocationUpdates(
				mGoogleApiClient, this);
	}

	/**
	 * Google api callback methods
	 */
	@Override
	public void onConnectionFailed(ConnectionResult result) {
		Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
				+ result.getErrorCode());
	}

	@Override
	public void onConnected(Bundle arg0) {

		// Once connected with google api, get the location
		displayLocation();

		if (mRequestingLocationUpdates) {
			startLocationUpdates();
		}
	}

	@Override
	public void onConnectionSuspended(int arg0) {
		mGoogleApiClient.connect();
	}

	@Override
	public void onLocationChanged(Location location) {
		// Assign the new location
		mLastLocation = location;

		Toast.makeText(getApplicationContext(), "Location changed!",
				Toast.LENGTH_SHORT).show();

		// Displaying the new location on UI
		displayLocation();
	}

}

References:
Making Your App Location-Aware

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
  • Julio Vergara

    Excellent Ravi, usefull tutorial

  • chantanz

    thanks Ravi for this nice tutorial

  • Sult’one

    Works perfectly, thank you Ravi 🙂

  • I am wondering you are still demoing using Eclipse! Setting dependencies and using them is damm easy in Android studio.

    Another thing is you have used LocationClient class, which is deprecated!

    • Alok Nair

      Hi Paresh,

      LocationClient is deprecated, but not LocationRequest. When did LocationRequest class become deprecated. 😛

      • Ohh yeah….that’s my mistake! I was talking about LocationClient only.

        • Got it. Let me check that … thanx 🙂

        • Alok Nair

          🙂

  • Adam

    Any chance of future tutorial using Android Studio as the IDE?

  • Raihan Rian

    Great tutorial …..brother …please make a weather app tutorial brother

  • Aguirre

    Why not Android Studio? Anyway! Still a great tutorial. Cheers!

    • I do use Android Studio. But I have to write a tutorial about AS first before publishing my articles using AS.

      • Aguirre

        I see. That’s pretty good. Start on basic to avoid confusion using the new IDE. Cheers!

        • Well said 🙂

          • Sumit

            Yes , waiting for Android Studio tutorial.

      • daniel dizzy

        Same here waiting for Android Studio Tutorials. Thanks Loads Ravi.

      • yes! please start creating tag for android studio and it has come to beta version ! i hope! @ravi8x:disqus

  • Arjun

    Hello Ravi, ” http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ ” .

    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.

  • karathb

    Gr8! Thx for it! Could you recommend a good geofencing tutorial?

  • Sai Nalla

    i am facing error in this tutorial
    it shows jar mismatch fix project dependencies how can i solve this
    my problem???

    • Try to replace the android-support-v4.jar with the jar that found in appcompat_v7 libs folder.

      • Sai Nalla

        hi

        Thats ok!!

        i have a small doubt how can i read a pdf file and highlighting the content in pdf in android mobile

        is there any app from u?

  • Vinay Maneti

    startLocationUpdates() and startLocationUpdates() methods are used to start/stop the location updates.

    In the above sentence the second method is stopLocationUpdates() but in the doc. is mentioned as startLocationUpdates().

    • Thank you vinay. Corrected now.

      • Guest

        (Y)

  • Allay Khalil

    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

  • SK

    Excellent Ravi, usefull tutorial, but i face problems to import import com.google.android.gms.location.LocationServices;.

    please help me…..:)

    • Did you added Google Play Services as library project?

  • Tono

    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?

    • Remove the casting, verify the import statements at the top.

  • John Antony

    Nice tutorial …. Which emulator you used in this tutorial bro?

    • Its a device bro. I used nexus5 to record the screen and then edited the video placing it on a mobile png image.

  • Dung

    Thanks tutorial.
    I have 20 location (have longitude, latitude) and save it in my database
    help me, how to get location near my location (have longitude, latitude)
    Ex: 10 meter
    😀

  • Amat Aj

    hi Ravi, I got this problem on

    import com.google.android.gms.location.LocationServices;

    it seems can’t be fix using Fix Project Setup..

  • sajid

    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

    • Is your device connected to internet?

      • sajid

        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;

        import android.app.Activity;

        import android.location.Location;

        import android.os.Bundle;

        import android.support.v4.app.FragmentActivity;

        import android.util.Log;

        import android.view.View;

        import android.widget.Button;

        import android.widget.TextView;

        import android.widget.Toast;

        import android.support.v4.app.FragmentActivity;

        import android.support.v7.app.ActionBarActivity;

        import android.os.Bundle;

        import android.view.Menu;

        import android.view.MenuItem;

        import com.google.android.gms.common.ConnectionResult;

        import com.google.android.gms.common.GooglePlayServicesUtil;

        import com.google.android.gms.common.api.GoogleApiClient;

        import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;

        import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;

        import com.google.android.gms.location.LocationListener;

        import com.google.android.gms.location.LocationRequest;

        import com.google.android.gms.location.LocationServices;

        import com.google.android.gms.maps.GoogleMap;

        import com.google.android.gms.maps.MapFragment;

        import com.google.android.gms.maps.OnMapReadyCallback;

        import com.google.android.gms.maps.model.LatLng;

        import com.google.android.gms.maps.model.MarkerOptions;

        public class MapLayoutActivity extends FragmentActivity implements ConnectionCallbacks,

        OnConnectionFailedListener, LocationListener {

        // LogCat tag

        private static final String TAG = MapLayoutActivity.class.getSimpleName();

        private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

        private Location mLastLocation;

        // Google client to interact with Google API

        private GoogleApiClient mGoogleApiClient;

        // boolean flag to toggle periodic location updates

        private boolean mRequestingLocationUpdates = false;

        private LocationRequest mLocationRequest;

        GoogleMap map;

        double latitude;

        double longitude;

        // Location updates intervals in sec

        private static int UPDATE_INTERVAL = 10000; // 10 sec

        private static int FASTEST_INTERVAL = 5000; // 5 sec

        private static int DISPLACEMENT = 10; // 10 meters

        // UI elements

        private TextView lblLocation;

        private Button btnShowLocation, btnStartLocationUpdates;

        @Override

        protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.map_layout);

        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

        // map.addMarker(new MarkerOptions().position(LOCATION_MEHDI).title(“Find me here!”));

        // mapFragment.getMapAsync(this);

        lblLocation = (TextView) findViewById(R.id.lblLocation);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);

        // First we need to check availability of play services

        if (checkPlayServices()) {

        // Building the GoogleApi client

        buildGoogleApiClient();

        createLocationRequest();

        }

        // Show location button click listener

        btnShowLocation.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View v) {

        displayLocation();

        }

        });

        // Toggling the periodic location updates

        btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View v) {

        togglePeriodicLocationUpdates();

        }

        });

        }

        @Override

        protected void onStart() {

        super.onStart();

        if (mGoogleApiClient != null) {

        mGoogleApiClient.connect();

        }

        }

        @Override

        protected void onResume() {

        super.onResume();

        checkPlayServices();

        // Resuming the periodic location updates

        if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {

        startLocationUpdates();

        }

        }

        @Override

        protected void onStop() {

        super.onStop();

        if (mGoogleApiClient.isConnected()) {

        mGoogleApiClient.disconnect();

        }

        }

        @Override

        protected void onPause() {

        super.onPause();

        stopLocationUpdates();

        }

        /**

        * Method to display the location on UI

        * */

        private void displayLocation() {

        mLastLocation = LocationServices.FusedLocationApi

        .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {

        latitude = mLastLocation.getLatitude();

        longitude = mLastLocation.getLongitude();

        lblLocation.setText(latitude + “, ” + longitude);

        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        map.addMarker(new MarkerOptions()

        .position(new LatLng(latitude,longitude))

        .title(“Marker”));

        } else {

        lblLocation

        .setText(“(Couldn’t get the location. Make sure location is enabled on the device)”);

        }

        }

        /**

        * Method to toggle periodic location updates

        * */

        private void togglePeriodicLocationUpdates() {

        if (!mRequestingLocationUpdates) {

        // Changing the button text

        btnStartLocationUpdates

        .setText(getString(R.string.common_google_play_services_network_error_text));

        mRequestingLocationUpdates = true;

        // Starting the location updates

        startLocationUpdates();

        Log.d(TAG, “Periodic location updates started!”);

        } else {

        // Changing the button text

        btnStartLocationUpdates

        .setText(getString(R.string.common_google_play_services_enable_button));

        mRequestingLocationUpdates = false;

        // Stopping the location updates

        stopLocationUpdates();

        Log.d(TAG, “Periodic location updates stopped!”);

        }

        }

        /**

        * Creating google api client object

        * */

        protected synchronized void buildGoogleApiClient() {

        mGoogleApiClient = new GoogleApiClient.Builder(this)

        .addConnectionCallbacks(this)

        .addOnConnectionFailedListener(this)

        .addApi(LocationServices.API).build();

        }

        /**

        * Creating location request object

        * */

        protected void createLocationRequest() {

        mLocationRequest = new LocationRequest();

        mLocationRequest.setInterval(UPDATE_INTERVAL);

        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);

        }

        /**

        * Method to verify google play services on the device

        * */

        private boolean checkPlayServices() {

        int resultCode = GooglePlayServicesUtil

        .isGooglePlayServicesAvailable(this);

        if (resultCode != ConnectionResult.SUCCESS) {

        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {

        GooglePlayServicesUtil.getErrorDialog(resultCode, this,

        PLAY_SERVICES_RESOLUTION_REQUEST).show();

        } else {

        Toast.makeText(getApplicationContext(),

        “This device is not supported.”, Toast.LENGTH_LONG)

        .show();

        finish();

        }

        return false;

        }

        return true;

        }

        /**

        * Starting the location updates

        * */

        protected void startLocationUpdates() {

        LocationServices.FusedLocationApi.requestLocationUpdates(

        mGoogleApiClient, mLocationRequest, this);

        }

        /**

        * Stopping location updates

        */

        protected void stopLocationUpdates() {

        LocationServices.FusedLocationApi.removeLocationUpdates(

        mGoogleApiClient, this);

        }

        /**

        * Google api callback methods

        */

        @Override

        public void onConnectionFailed(ConnectionResult result) {

        Log.i(TAG, “Connection failed: ConnectionResult.getErrorCode() = ”

        + result.getErrorCode());

        }

        @Override

        public void onConnected(Bundle arg0) {

        // Once connected with google api, get the location

        displayLocation();

        if (mRequestingLocationUpdates) {

        startLocationUpdates();

        }

        }

        @Override

        public void onConnectionSuspended(int arg0) {

        mGoogleApiClient.connect();

        }

        @Override

        public void onLocationChanged(Location location) {

        // Assign the new location

        mLastLocation = location;

        Toast.makeText(getApplicationContext(), “Location changed!”,

        Toast.LENGTH_SHORT).show();

        // Displaying the new location on UI

        displayLocation();

        }

        @Override

        public boolean onCreateOptionsMenu(Menu menu) {

        // 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?

  • good work.

  • Lee

    i tried this but i m not able to see n e thing…it says “Unfortunately LocationApp has stopped”
    i was trying to run it on emulator…..what can i do ???
    there are no errors ….. help me

  • Brijesh Thumar

    why you are not use Android Studio ?

    • Why should he ?
      Eclipse is better than AS.

      • Back Packer

        No AS is better ! 😀

      • Viraj

        you probably have not used the stable version..

  • Wealthy

    I ravi Its not working for me or maybe i cant get it to work..are u on skype?

  • Ravi,I’ve a doubt

    CODE 1 :

    private static int UPDATE_INTERVAL = 10000;

    private static int FATEST_INTERVAL = 5000;

    private static int DISPLACEMENT = 10;

    CODE 2:

    private static int UPDATE_INTERVAL = 10000,

    FATEST_INTERVAL = 5000,

    DISPLACEMENT = 10;

    Does it cause any problem in future if i use CODE2 instead of CODE1 ?

    (In brief, What is the problem if we declare variables in a single line if they share the same characteristics ?).

    it may be a foolish qstn, don’t laugh.. am a newbie 😉

    • No problem at all. Actually its a good practise too. But I used that way for readability.

  • vinod

    hi, all the posts you have given are outstanding…what is the source you are following.. any books,websites or any other stuff?

  • 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

    • If you are testing on emulator, make sure that you are using > 4.0 version.

      • Abubaker

        Hi.. I downloaded the code and tried to run. First it was giving error at AppTheme. removed it and then tried running the app, it is not running. Getting error “AppName stopped unexpectedly”

  • manvi

    hello sir … this tutorial is awesome …. u r saviour of my job ..
    can u please help me that how can i get location of other devices … please sir .. its humble request

  • Abhishek Patil

    Hi ravi, I just modified the displayLocationMethod(), so now we can get the actual name of the place from Current Latitude and Longitude with the help of Geocoder.

    /**
    * Method to display the location on UI
    * */

    private void displayLocation() {

    mLastLocation = LocationServices.FusedLocationApi

    .getLastLocation(mGoogleApiClient);

    if (mLastLocation != null) {

    double latitude = mLastLocation.getLatitude();

    double longitude = mLastLocation.getLongitude();

    // lblLocation.setText(latitude + “, ” + longitude);

    Geocoder geocoder= new Geocoder(this, Locale.ENGLISH);

    try {

    //Place your latitude and longitude

    List addresses = geocoder.getFromLocation(latitude,longitude, 1);

    if(addresses != null) {

    Address fetchedAddress = addresses.get(0);

    StringBuilder strAddress = new StringBuilder();

    for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++)
    {

    strAddress.append(fetchedAddress.getAddressLine(i)).append("n");

    }

    lblLocation.setText("You're at: " +strAddress.toString());

    }

    else{

    lblLocation.setText("No location found..!");

    }

    catch (IOException e) {
    e.printStackTrace();
    Toast.makeText(getApplicationContext(),"Could not get address..!", Toast.LENGTH_LONG).show();
    }

    }

    else {

    lblLocation.setText("(Couldn't get the location. Make sure location is enabled on the device)");

    }

    }

    • manvi

      hello … have u worked by finding location of other persons??

  • Christian

    Hi Ravi, amazing tutorial, I was wondering why you need to start up other apps with locations (e.g. Google Maps)? Is this not only needed for PRIORITY_NO_POWER ?

  • Richa Khanna

    Hey Ravi, I wanted to know why are you calling startLocationUpdate in onResume() when it’s already being called on onConnected? Isn’t startLocationUpdate will be fired when onConnected will be called.

  • SHON

    Hey when i call startlocationupdate on create it gives me error

    google api client is not connected yet
    plz help

  • Deepak

    hi Ravi..

    I am getting this runtime error.

    03-29 00:38:40.109: E/AndroidRuntime(25114): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.ni/com.example.ni.MainActivity}: java.lang.ClassNotFoundException: Didn’t find class “com.example.ni.MainActivity” on path: DexPathList[[zip file “/data/app/com.example.ni-2/base.apk”],nativeLibraryDirectories=[/vendor/lib, /system/lib]]

    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

        • Arun Bisht

          Hi Ankita, Open sdk manager->Extras->google play services(API 21) -> Install

  • No game No life

    Anyone knows any tutorials on making app like this one http://i.stack.imgur.com/D8aMp.jpg

  • Manaal Maniyar

    Hi Ravi,

    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.

  • Syed Aamir

    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.

            https://www.dropbox.com/s/1rns5dt032dlh2i/LocationService.java?dl=0

            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.

  • Abdul Khaliq

    LocationServices is not importing anyone help me to solve this problem. plz give me solution as soon as early thanks in advance to them

  • implements ConnectionCallbacks,
    OnConnectionFailedListener

    Not Resolve in Android Studio

    I have imported compile ‘com.google.android.gms:play-services:7.5.0’

    then also its not work for me.

    • Jigar

      implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener

      use this implements

  • Xavi (Drakgoku1)

    Hi, you save my day, thanks !

  • mohan

    how to implement google map in my application

  • mohan

    plz send demo on mohanchaudhari9@gmail.com

  • amiya

    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…

  • Suresh Nagarajan

    Hi. Wonderful program which works perfectly and a complete example using the Google Play Services API. which requires no services

    To update location when the app is in the back ground, no big changes need to be made
    Do not call the stopLocationUpdates() in the onPause() and do not disconnect the mGoogoleApiClient in the onStop

    You will have to do both of the above in the onBackPressed() to stop the updates

  • Rein

    E/GMPM: getGoogleAppId failed with status: 10
    E/GMPM: Uploading is not possible. App measurement disabled

    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

  • Guys start using Android Studio

  • Thili_Bu

    Hi
    Can I improve this code to obtain address of a place using the longitudes latitudes that has been obtained.

  • Miguel Angel Posada

    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).

  • Manivel.m

    hai sir google location find in android studio in source code link plz help me sir

  • Harsh Balyan

    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..

    Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet.

    pointing to the code :

    @Override
    protected void onPause()
    {
    super.onPause();
    => stopLocationUpdates();
    }

    protected void stopLocationUpdates() {
    => LocationServices.FusedLocationApi.removeLocationUpdates(
    mGoogleApiClient, this);
    }

    If anyone come across this exception please reply. Thanks in advance.

    • Rak

      the exception clearly says that the GoogleApiClient is not connected. You should add this code wherever you are using mGoogleApiClient –

      if ((mGoogleApiClient != null) && (mGoogleApiClient.isConnected()) {
      // valid client API handle do something
      }

  • frans1t1

    Hi Ravi,

    i got problem if touch back button, application is Force Close
    can fix that.

  • Gautam

    if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
    startLocationUpdates();
    }
    i am getting error at this line inside onResume it is showing null pointer exception

  • yoad

    i think gps still working after stopping (moving to background) the app.
    anyone else encountered that, or knows what to do?
    (gps still blinks even after calling stopUsingGPS in the onStop method)

  • Messaoudi Heni

    It works.
    thanks you save my day
    But you should just add the permession check for location to work without any error

  • Nithin

    how to enable gps settings without close the app.(when location settings is off)?

    • I think it’s not possible.

      • Nithin

        i get some code in “Prompt the User to Change Location Settings” in https://developer.android.com/training/location/change-location-settings.html#prompt

        but i have no idea how to implement in non activity class(Service).plzz help me

        Thanks in advance);

        • Can you write down the lines of code which is not available in non-activity class.

          • Nithin

            my point is how can we create dialog in non activity class?
            is it possible?

            // Show the dialog by calling startResolutionForResult(),
            // and check the result in onActivityResult().
            status.startResolutionForResult(
            (Activity) getApplicationContext(), 1000);

            This code usind in my non Activity class but how can i resove “Acivity” in my class.?

            Thanks for ur great consideration );

  • Navya Ramesan

    I cannot locate libprojectgoogle-play-services_lib in google_play_services folder, I am using Eclipse with ADT 23.0.7. What is the possible reason?

    • Use Android Studio. You won’t get much benefits from Eclipse now.

      • Navya Ramesan

        Yes you’re right, but I needed a solution on Eclipse.

  • heeeelp

    i have error ” Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet.”
    help

    • mitchell harrison

      For those who are having this problem, it’s probably because you’ve not checked to see if mGoogleApiClient is not null in the OnResume.
      if (mGoogleApiClient != null) {
      mGoogleApiClient.connect();
      }

      This is if you haven’t used the updated version of the latter half of this tutorial.

    • Farooq Khan

      Follow the tutorial here, It has check for this exception: http://androidtechpoint.blogspot.com/2017/01/android-tutorial-to-get-last-known.html

  • HemaNandhini

    hi,nice tutorial,can you please help me to find out my near friends locations using gps tracker.

  • MarkNguyen

    Nice tutorial, but I don’t know why you use “synchronized” in “buildGoogleApiClient” because it is only called in onCreate().

  • Sam

    I got error on ‘isGooglePlayServicesAvailable’ is not deprecated. I copy all the codes exactly as shown above. Could you please help

  • Raúl Garcia

    is thee a way to port this code into a service????

  • sameer khan

    will this work if I turn off my location services ?

  • Tammana

    Hi, i found an very interesting app. Get a Free App Downloaded for school and College quiz.

    https://play.google.com/store/apps/details?id=com.rahulmalhotra.johnwick.buzzer&hl=en

  • Aqsa Shahid

    what if i want to show that location on the map…??

  • Hemtech

    This worked like Magic, thanks

  • Aakash Kumar Chauhan

    Unfortunately app has stopped 🙁

  • Venkatesh Narayanan

    Hello Ravi this api is not working in htc desire 820. Could you please tell me how to fix.

  • Usup Suparma

    i have problem with this code
    LocationServices.FusedLocationApi.requestLocationUpdates(
    mGoogleApiClient, mLocationRequest, this);

    message error “call request permision which may be rejected by user: code should explicity check to see if permision is available

    • Saurav vishal

      Just do alt+enter there on the code and select add check permissions, it will automatically add the required permission check.

      • Usup Suparma

        yes i do it. but my application do not have anything to show location..

  • Have you copied google-services.json to app folder?

    • Yawo Dagbeneva Djilan

      No because I don’t know where the file is.
      please where can I find it ?

      • You have to download this file Google console dashboard while configuring the project

        • Yawo Dagbeneva Djilan

          OK I have downloaded the google-services.json file and put it where you told me.
          now the problen is that the instruction

          LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
          return always null

          • Is runtime permissions are added?

          • Yawo Dagbeneva Djilan

            Yes even if I add runtime permissions no change.
            I want to know if my android version ( 6.0) can be the cause.

  • Yusmery Riera

    thanks you saved me with this!! Work fine in samsung and motorola, you know some device where isn’t work?

    • Satnam Singh

      hi this is not working in Samsung Galaxy On8.. Could you please help me here..even it does not work when I have given permission of location manually ..

  • Vinicius de Paula

    Please, how to hide de GPS icon?

  • Satnam Singh

    hi this is not working in Samsung Galaxy On8 and others
    .. Could you please help me here..even it does not work when I have given permission of location manually ..