Search code examples
androidbroadcastreceiverandroid-serviceandroid-fusedlocation

Best practices: Getting location updates in background


Developing an android application which updates location of the user in the background. Now, for this Google provide two ways:

  1. Getting user last location through getlastlocation() function. An alarm manager can be set and with the help of broadcast receiver and a service, location can be updated continuously. For example:

  2. Request periodic updates from the fused location provider as shown here

Which way is the best way to get location updates in the background continuously without Android killing the background service unless user does so?


Solution

  • The second method "requesting periodic location updates" is active. It allows you to more specifically tailor the frequency of updates and under what circumstances you will get an update. You are telling Android that you want to be updated so often and/or if the user has moved more than X meters.

    The first method using getLastLocation() is passive. It means you have no control over the frequency or quality of the updates. You are basically piggybacking on top of other application's location update requests. If there are other applications that have asked for frequent updates then calling getLastLocation() will give you a relatively recent/accurate location. If, however, other applications are not requesting frequent updates (or maybe the user isn't running any other applications at all), calls to getLastLocation() will likely return very stale (inaccurate/old) data.