Android : LocationManager vs Google Play Services
Asked Answered
S

9

175

I want to build an app that centers around getting the user's current location and then find points of interest(such as bars,restaurants,etc) that are close to him/her via the Google Places API.

Upon searching the web for a place to start I came across some tutorials that use the LocationManager class and some others that use Google Play Services in order to find the users location.

On first sight both of them do the same thing, but since I am new to this I got a little confused and I don't know which method suits my needs the best. So, I want to ask you :

What are the differences between these two methods of finding locations (if there are any) ?

Seamark answered 8/10, 2015 at 17:48 Comment(1)
visit here #21397677Elayneelazaro
V
357

User Location on Android

Getting the user’s location on Android is a little less straightforward than on iOS. To start the confusion, there are two totally different ways you can do it. The first is using Android APIs from android.location.LocationListener, and the second is using Google Play Services APIs com.google.android.gms.location.LocationListener. Let’s go through both of them.

  1. Android’s Location API

    The Android’s location APIs use three different providers to get location -

    • LocationManager.GPS_PROVIDER — This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix.
    • LocationManager.NETWORK_PROVIDER — This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup.
    • LocationManager.PASSIVE_PROVIDER — This provider will return locations generated by other providers. You passively receive location updates when other applications or services request them without actually requesting the locations yourself.

The gist of it is that you get an object of LocationManager from the system, implement the LocationListener, and call the requestLocationUpdates on the LocationManager.

Here’s a code snippet:

    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      // Called when a new location is found by the network location provider.
      makeUseOfNewLocation(location);
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}

    public void onProviderEnabled(String provider) {}

    public void onProviderDisabled(String provider) {}
  };

// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

Google’s API Guide on Location Strategies explains the code pretty nicely. But they also mention that in most cases, you’ll get better battery performance, as well as more appropriate accuracy, by using the Google Location Services API instead. Now the confusion starts!

  1. Google’s Location Services API

Google’s Location Services API is a part of the Google Play Services APK (here’s how to set it up) . They’re built on top of Android’s API. These APIs provide a “Fused Location Provider” instead of the providers mentioned above. This provider automatically chooses what underlying provider to use, based on accuracy, battery usage, etc. It is fast because you get location from a system-wide service that keeps updating it. And you can use more advanced features such as geofencing.

To use the Google’s Location Services, your app needs to connect to the GooglePlayServicesClient. To connect to the client, your activity (or fragment, or so) needs to implement GooglePlayServicesClient.ConnectionCallbacks and GooglePlayServicesClient.OnConnectionFailedListener interfaces. Here’s a sample code:

    public class MyActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
    LocationClient locationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        locationClient = new LocationClient(this, this, this);
    }

    @Override
    public void onConnected(Bundle bundle) {
    Location location = locationClient.getLastLocation() ;
        Toast.makeText(this, "Connected to Google Play Services", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDisconnected() {
    Toast.makeText(this, "Connected from Google Play Services.", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // code to handle failed connection
        // this code can be found here — http://developer.android.com/training/location/retrieve-current.html 
    }
  • Why is locationClient.getLastLocation() null?

The locationClient.getLastLocation() gets the last known location from the client. However, the Fused Location Provider will only maintain background location if at least one client is connected to it. Once the first client connects, it will immediately try to get a location. If your activity is the first client to connect and you call getLastLocation() right away in onConnected(), that might not be enough time for the first location to come in. This will result in location being null.

To solve this issue, you have to wait (indeterminately) till the provider gets the location and then call getLastLocation(), which is impossible to know. Another (better) option is to implement the com.google.android.gms.location.LocationListener interface to receive periodic location updates (and switch it off once you get the first update).

    public class MyActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
    // . . . . . . . . more stuff here 
    LocationRequest locationRequest;
    LocationClient locationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // . . . . other initialization code
        locationClient = new LocationClient(this, this, this);
    locationRequest = new LocationRequest();
    // Use high accuracy
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // Set the update interval to 5 seconds
    locationRequest.setInterval(UPDATE_INTERVAL);
        // Set the fastest update interval to 1 second
    locationRequest.setFastestInterval(FASTEST_INTERVAL);
    }
    // . . . . . . . . other methods 
    @Override
    public void onConnected(Bundle bundle) {
        Location location = locationClient.getLastLocation();
        if (location == null)
            locationClient.requestLocationUpdates(locationRequest, this);
        else
            Toast.makeText(getActivity(), "Location: " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_SHORT).show();
    }
    // . . . . . . . . other methods
    @Override
    public void onLocationChanged(Location location) {
        locationClient.removeLocationUpdates(this);
        // Use the location here!!!
    }

In this code, you’re checking if the client already has the last location (in onConnected). If not, you’re requesting for location updates, and switching off the requests (in onLocationChanged() callback) as soon as you get an update.

Note that the locationClient.requestLocationUpdates(locationRequest, this); has to be inside the onConnected callback, or else you will get an IllegalStateException because you will be trying to request for locations without connected to the Google Play Services Client.

  • User has disabled Location Services

Many times, the user would have location services disabled (to save battery, or privacy reasons). In such a case, the code above will still request for location updates, but onLocationChanged will never get called. You can stop the requests by checking if the user has disabled the location services.

If your app requires them to enable location services, you would want to show a message or a toast. Unfortunately, there is no way of checking if the user has disabled location services in Google’s Location Services API. For this, you will have to resort back to Android’s API.

In your onCreate method:

    LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
    locationEnabled = false;
    Toast.makeText(getActivity(), "Enable location services for accurate data", Toast.LENGTH_SHORT).show();
}
else locationEnabled = true;

And use the locationEnabled flag in your onConnected method like this:

    if (location != null) {
    Toast.makeText(getActivity(), "Location: " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_SHORT).show();
}
else if (location == null && locationEnabled) {
    locationClient.requestLocationUpdates(locationRequest, this);
}

UPDATE

Document is updated, LocationClient is removed and the api supports to enable GPS with one click from dialog:

task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
    // All location settings are satisfied. The client can initialize
    // location requests here.
    // ...
}
});

task.addOnFailureListener(this, new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        if (e instanceof ResolvableApiException) {
            // Location settings are not satisfied, but this can be fixed
            // by showing the user a dialog.
            try {
                // Show the dialog by calling startResolutionForResult(),
                // and check the result in onActivityResult().
                ResolvableApiException resolvable = (ResolvableApiException) e;
                resolvable.startResolutionForResult(MainActivity.this,
                        REQUEST_CHECK_SETTINGS);
            } catch (IntentSender.SendIntentException sendEx) {
                // Ignore the error.
            }
        }
    }
});

Link https://developer.android.com/training/location/change-location-settings#prompt

New location client: FusedLocationProviderClient

  private FusedLocationProviderClient fusedLocationClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}

It is recommended to go through https://developer.android.com/training/location before doing any location tasks.

Vern answered 8/10, 2015 at 18:55 Comment(9)
You can use SettingsApi.checkLocationSettings()to check whether the user has enabled Location Services (see here: developers.google.com/android/reference/com/google/android/gms/…).Anomie
LocationClient does not exist anymore. For an updated and clear guide to Location, please check this article: blog.teamtreehouse.com/beginners-guide-location-androidPapyrology
And training page with SettingsApi example: developer.android.com/training/location/…Wayzgoose
You can also create a geo-fence using LocationManager! Does the fused location api works on devices which doesn't have google play services?Contraception
This can be another better way to check GPS enable/disable status fun isLocationEnabled(context: Context): Boolean { val locationMode: Int try { locationMode = Settings.Secure.getInt( context.contentResolver, Settings.Secure.LOCATION_MODE ) } catch (e: SettingNotFoundException) { e.printStackTrace() return false } return locationMode != Settings.Secure.LOCATION_MODE_OFF }Omission
developer.android.com/guide/topics/location/strategies.html -> 404Geminian
Rahul Jiresal link mentioned in the answer is leading to the XXX website.Advent
Thanks @MuhammadIrfan for the report. That link was working before.Vern
@Vern could you please take a look at this question regarding location? #74284932Shoreless
B
40

In my experience, "more appropriate accuracy" doesn't mean better by any means. Unless I'm missing something, if you want to make sure GPS is used, LocationManager is the only way to go. We track vehicles with our app and, again, unless I'm missing something, Google Play Services provides some very inaccurate locations quite often.

Burleigh answered 30/11, 2015 at 17:14 Comment(2)
Yes, from my experience Google Play Services some times provide inaccurate location.Shope
Yes, the Google Play Services Location Services API can give very misleading Location info. WiFi modems get moved, WiFi modems get updated with incorrect location information (ie if location is spoofed by an Android device that updates the WiFi modem's location) and there are a host of other circumstances that can result in incorrect Location data from WiFi modem triangulation. In all our apps where precise Location is mandatory, we use GPS only.Douse
A
30

I have been using the Google Location Services API for quite a while. It does have advantages, since it encapsulates the complexity of having several sources for determining positions. However it encapsulates too heavily, so that when you get a strange position, you have no way to determine where that strange position came from.

In real life I have had several freak values pop up, being 10's of kilometers away from the actual position. The only explanation is that these crazy locations stem from errors in Googles Wi-Fi or NWK databases - errors which will always be there, since Wi-Fi and Network topologies change every day. But unfortunately (and surprisingly) the API gives you no information as to how an individual position was derived.

enter image description here

This leaves you with the problems of having to filter out freak values based on plausibility checking on speed, acceleration, bearing etc.

... or go back to the good old framework API and use GPS only, which is what I decided to do until Google improves the fused API.

Amari answered 12/8, 2017 at 12:55 Comment(0)
M
28

You should use the Google Play Services location api instead of LocationManager. According to the docs:

The Google Play services location APIs are preferred over the Android framework location APIs (android.location) as a way of adding location awareness to your app. If you are currently using the Android framework location APIs, you are strongly encouraged to switch to the Google Play services location APIs as soon as possible.

As to why to switch, Google says this:

The Google Location Services API, part of Google Play Services, provides a more powerful, high-level framework that automatically handles location providers, user movement, and location accuracy. It also handles location update scheduling based on power consumption parameters you provide. In most cases, you'll get better battery performance, as well as more appropriate accuracy, by using the Location Services API.

Misbelief answered 8/10, 2015 at 17:58 Comment(4)
Do you have links to that documentation that these quotes are from? It would be interesting to see if Google is saying anything different now.Spyglass
Of course they say this, because they want your location data!Funkhouser
When you add Google play services to your app, if a user installs your app, he will be prompted to "update" google play services to use your app. In case his / her phone is nearly full( with whatsapp memes and stuff) or the user doens't have the data, sorry for you my friendIncisor
@Funkhouser Yep! Lol, the way they word it makes it sound like it's a magical solution! The hugest drawback is that you need Google Play Services on the device!!!Monmouth
A
9

Diffferences between the two apis Google Play Service Location API and Android Framework Location API based on GPS service

FusedLocationProviderClient

  1. For the 1st fetch, the location must not be null(i.e: Some other app need to update the Lastknown location in the GoogleplayService database. if it is null, need work around)
  2. For the next sequential Fetch, it uses requestLocationUpdates() method to fetch the location.
  3. The location fetch is only based on locationRequest.setInterval(milliseconds)and setFastestInterval(milliseconds), not based on user location change
  4. The LatLng value returned has contain only 7 decimal values (e.g: 11.9557996, 79.8234599), not as accurate
  5. Recommended, when your app requirement takes current location distance negligible of (50 - 100 meters accuracy)
  6. Effective in Battery usage.

LocationManager Api

  1. The user location fetch is invoked using locationManager.requestLocationUpdates()
  2. The location fetch based on user location change and time intervals locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, milliseconds, mindistance, Mylocationlistener)

  3. The LatLng value returned has contain 14 decimal values (e.g: 11.94574594963342 79.81166719458997) accurate location values

  4. Recommended for location based app, when needs more accuracy even in meters.
  5. Battery usage is based on fetch interval and fetch distance.
Assisi answered 9/8, 2019 at 4:58 Comment(2)
hey! 1° is at most 111_111 meters (20_000_000 / 180). So, 0.0000001° is 0.011m = 1 cm. I don't know where do you need better GPS resolution. And I don't even know, how can you achieve better GPS resolution.Cangue
@Assisi Could you please take a look at this question : #74284932Shoreless
F
8

The Google Location Services API, part of Google Play Services, provides a more powerful, high-level framework that automatically handles location providers, user movement, and location accuracy. It also handles location update scheduling based on power consumption parameters you provide. In most cases, you’ll get better battery performance, as well as more appropriate accuracy, by using the Location Services API.

More detailed diffferences between the two apis Google Play Service Location API and Android Framework Location API can be found here

Funke answered 5/10, 2016 at 9:49 Comment(3)
I used your answer to answer my own question if that's ok. Thanks a lot! #39853455Oneway
@Oneway so don't you think my answer deserves upvote?Funke
That's a 3year old document. But here's a plus 1Conflict
D
6

Yes, the Google Play Services Location Services API can give very misleading Location info. WiFi modems get moved, WiFi modems get updated with incorrect location information (ie if location is spoofed by an Android device that updates the WiFi modem's location) and there are a host of other circumstances that can result in incorrect Location data from WiFi modem triangulation. In all our apps where precise Location is mandatory, we use GPS only.

Douse answered 20/7, 2019 at 23:20 Comment(0)
C
1

Android Location

LocationManager - Context.getSystemService(Context.LOCATION_SERVICE)

  • ACCESS_COARSE_LOCATION - provide less accurate location(city block) but faster and does not drain a battery so much

    • NETWORK_PROVIDER - uses cell towers, wifi access points
    • PASSIVE_PROVIDER - subscribes on location updates when somebody else in the system uses another providers
  • ACCESS_FINE_LOCATION - provides better and accurate location(up to few meters). Uses the same providers as ACCESS_COARSE_LOCATION

    • GPS_PROVIDER - satellites are used

Google API Location Services - GoogleApiClient based on Google Play Services. High level API with access to location events which go through the system. It has better battery performance but could not be installed on some devices

  • Fused Location Provider - automatically select an appropriate provider based on your needs and device conditions
Champagne answered 9/3, 2021 at 14:1 Comment(0)
R
0

Adding to the accepted answer, when enabling GPS through AlertDialog solution provided by Google. The implementation with ActivityResultContract is as follows:

// Global Activity Scope

ActivityResultLauncher<IntentSenderRequest> gpsRequestLauncher = registerForActivityResult(
        new ActivityResultContracts.StartIntentSenderForResult(), callback -> {
        if(callback.getResultCode() == RESULT_CANCELED) {
            // Request Cancelled
        } else {
            //  GPS Enabled
        }
});

Since the code from documentation is outdated with deprecation of onActivityResults

task.addOnFailureListener(this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            if (e instanceof ResolvableApiException) {
                // Location settings are not satisfied, but this can be fixed
                // by showing the user a dialog.
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    IntentSenderRequest request = new IntentSenderRequest.Builder(
                        e.resolution).build();
                    gpsRequestLauncher.launch(request);
                } catch (IntentSender.SendIntentException sendEx) {
                    // Ignore the error.
                }
            }
        }
    });
Rummer answered 4/3, 2022 at 13:18 Comment(1)
Could you please take a look at this question : #74284932Shoreless

© 2022 - 2024 — McMap. All rights reserved.