149

If we go through the documentation of the LocationClient, we can see that the class is deprecated.

But the deprecated class is used in the documentation to get the current location.

I think this is little bit misleading or am i looking at incorrect documentations?

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
George Mathew K
  • 1,580
  • 2
  • 10
  • 5
  • 6
    As always, they deprecate apis but they don't update the docs at the same time. You'll have to wait until the docs are updated or try to find a working example – Imanol Jul 10 '14 at 10:53

6 Answers6

271

Again Google has released a new API but they haven't updated the documentation :$ After spend some time trying to figure out how it works I got it, here you have a full example using the new/latest Location Service API... Enjoy developing :)

import android.location.Location;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
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
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private final String TAG = "MyAwesomeApp";

    private TextView mLocationView;

    private GoogleApiClient mGoogleApiClient;

    private LocationRequest mLocationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mLocationView = new TextView(this);

        setContentView(mLocationView);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Connect the client.
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        // Disconnecting the client invalidates it.
        mGoogleApiClient.disconnect();
        super.onStop();
    }

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(1000); // Update location every second

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

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "GoogleApiClient connection has been suspend");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(TAG, "GoogleApiClient connection has failed");
    }

    @Override
    public void onLocationChanged(Location location) {
        mLocationView.setText("Location received: " + location.toString());
    }
}

and do not forget to add this permissions to your AndroidManifest.xml file:

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

Note: if you just need to get the last location (without updates), you can use LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient) from OnConnected

Androider
  • 441
  • 2
  • 6
  • 17
Diego Palomar
  • 6,958
  • 2
  • 31
  • 42
  • Thanks for the example. In the [tutorial](http://developer.android.com/training/location/retrieve-current.html) on the Google Dev Site, there was an _To check that the APK is installed, call `GooglePlayServicesUtil.isGooglePlayServicesAvailable()` ..._ part. Is that necessary here, also? Where should I put that part? – Nagy Vilmos Aug 29 '14 at 12:44
  • Nagy, you check for google play service right before the mGoogleApiClient.connect() call, and only connect if the value = ConnectionResult.SUCCESS – Alchete Sep 13 '14 at 17:10
  • 3
    Is there a similar code example on how to use the LocationServices.GeofencingAPI? – InquisitorJax Nov 20 '14 at 12:27
  • 1
    Good answer. Just merge it with some old components/stuff and everything works like a charm. – MiguelHincapieC Nov 28 '14 at 20:04
  • Some questions: Is there a call back if the Location Request failed? Or is the same callbacks for the Google API client used for this is well? – Ersen Osman Dec 10 '14 at 21:35
  • 2
    Note that if you just want to get the last location without updates, you can use `LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);` from OnConnected – Stevie Kideckel Dec 11 '14 at 22:13
  • 1
    How would you go about stopping an on-going location request? – Ersen Osman Dec 12 '14 at 21:30
  • 1
    This should be marked as the correct answer, it was just what I was looking for thnaks! – Gerson Sosa Dec 14 '14 at 12:35
  • 1
    Thanks. It's crazy Google still haven't updated their API docs. Bug filed here https://code.google.com/p/android/issues/detail?id=82907 probably a duplicate - but hey. They deserve it :) – Espen Riskedal Dec 17 '14 at 17:30
  • @InquisitorJax I second that. Does anyone know how to add Geofencing to this? Can't find it anywhere and the docs are outdated. – Rich Luick Dec 30 '14 at 21:49
  • 1
    You don't need `` . `` includes both. – aandis Jan 28 '15 at 14:05
  • Once again, really lousy handling of library updates by Google! – Price Mar 09 '15 at 14:45
  • Notice, that without `mLocationRequest.setInterval(1000);` (or any other interval) you won't get any location updates. Took me some time to find that out... – Torben Kohlmeier Apr 12 '15 at 11:13
  • did not work despite i change the location by lots of meters –  Nov 29 '15 at 13:26
  • Hey this is working well +1 for this. But how can I use this code to get user location even in background? Or how can I use this code as `service` ?? – Kaushal28 Sep 05 '16 at 04:17
  • @NoOne yes of course, you can use that code from a Service and it will work like a charm – Diego Palomar Sep 05 '16 at 09:29
  • But I cant figure out how to do this. Can you please answer this question for me? It has same problem: http://stackoverflow.com/questions/39327713/how-to-use-google-location-service-api-to-get-location-updates-even-in-backgroun Please add sample code. Thanks in advance! :) – Kaushal28 Sep 05 '16 at 12:47
  • 1
    Okay thank you very much. This is working perfect in `service` class also :) – Kaushal28 Sep 05 '16 at 15:22
  • 5
    FusedLocationApi is deprecated –  Oct 23 '17 at 17:56
  • could be good to have the conversion of the given sample to the new FusedLocationProviderClient as now FusedLocationApi is deprecated – zeus Apr 05 '18 at 18:30
  • 'com.google.android.gms.common.api.GoogleApiClient' is deprecated Inspection info: Reports where deprecated code is used in the specified inspection scope. – Arnold Brown Dec 23 '20 at 07:12
  • GoogleApiClient is deprecated – Gyan Swaroop Awasthi Jul 27 '21 at 17:09
22

Some of the documentation is old in Google (some examples you mentioned still use the deprecated LocationClient). You have to use the new GoogleApiClient as described in the location Services examples:

private GoogleApiClient mGoogleApiClient;

  mGoogleApiClient = new GoogleApiClient.Builder(context)
     .addApi(LocationServices.API)
     .addConnectionCallbacks(this)
     .addOnConnectionFailedListener(this)
     .build()

and when the new client is connected, you can use the fused location api for example like this:

LocationServices.FusedLocationApi.requestLocationUpdates(theNewClient, 
    locationRequest, locationListener);
King of Masses
  • 18,405
  • 4
  • 60
  • 77
paularius
  • 241
  • 1
  • 6
4

It looks like this was covered in the developer blog. For LocationClient, you'd use this in conjunction with LocationServices which then leads us to GeofencingApi.

Sofi Software LLC
  • 3,879
  • 1
  • 36
  • 34
  • 6
    Six months later after the release of that new Google Play API and the documentation has not yet been updated. – AxeEffect Aug 23 '14 at 11:08
  • 1
    It also looks like the official LocationProvider app from Google is still using the LocationClient which no longer exist inside this package import com.google.android.gms.location.LocationClient; – Simon Dec 28 '14 at 19:02
4

LocationClient is removed. GoogleApiClient is api to use for Google Play services Location APIs.

The sample code for the common scenarios is here and the training classes were updated with more coming soon.

PaulR
  • 3,223
  • 1
  • 21
  • 32
0

According to the documentation update code..

package iwannado.com.myapplicationforsha1key;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Geocoder;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.identity.intents.Address;
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.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;

public class MapWithMapViewActivity extends AppCompatActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private static final String TAG = MapWithMapViewActivity.class.getCanonicalName();


    private GoogleMap mMap = null;
    private MapView mMapView = null;

    private EditText loatcationEditText = null;

    private GoogleApiClient mGoogleApiClient = null;
    private Location mLocationRequest = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_with_map_view);
        loatcationEditText = (EditText) findViewById(R.id.loatcation_edit_text);
        mMapView = (MapView) findViewById(R.id.mapView);
        /*
        * The method is used to create mapView
        * */
        mMapView.onCreate(savedInstanceState);
        /*
        *The method Return Google map
        * */
        mMapView.getMapAsync(this);

        gotoCurrentLoactionGooglePlayService();
    }

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


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

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

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

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;



    }



    private void gotoCurrentLoactionGooglePlayService() {
        /*working with new google api for laction..
http://stackoverflow.com/a/25173057
* */
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }



    @Override
    public void onConnected(@Nullable Bundle bundle) {
/*
* Follow this documentation.. https://developer.android.com/training/location/retrieve-current.html
*
* Please add Runtime permission here for android 6
* */
        mLocationRequest = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLocationRequest != null) {

           LatLng latLng = new LatLng(mLocationRequest.getLatitude(),mLocationRequest.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng).title("Programmatically Current Loaction"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            Toast.makeText(this,"getLatitude() = "+String.valueOf(mLocationRequest.getLatitude())+"\n getLongitude() = "+String.valueOf(mLocationRequest.getLongitude()),Toast.LENGTH_LONG).show();

        }
    }


    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "GoogleApiClient connection has been suspend");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i(TAG, "GoogleApiClient connection has failed");
    }

    @Override
    public void onLocationChanged(Location location) {


        Toast.makeText(this,"Location received: " + location.toString(),Toast.LENGTH_LONG).show();

    }
}
Muhammad Waleed
  • 2,517
  • 4
  • 27
  • 75
0

You just simply add this in your code,

private FusedLocationProviderClient mFusedLocationClient;
private Location mLastLocation;

 oncreate(){
  .
  .
  FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
   if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            mLastLocation =location;
            if (mLastLocation!= null) {
                LogUtils.logE(TAG, "Lat: " + mLastLocation.getLatitude() + "Long: " + mLastLocation.getLongitude());
            }

        }
    });
  .
  .
  }

According to the documentation update code..