androidlocationmanagerlocation-provider

Execute code on location changes if app not running


I'm writing a small android app that need to execute some code when the devise change location. I was wondering if it is possible to execute code on location change even if the app is not running (not background but stopped). I mean, is there some system services that "wake" (or launch) my app (or a specific activity of my app) when lat/lng changes?

Until now I've create a locationManager, set some criteria, a provider and set the requestLocationUpdates. This is working but if the app is not running I got no update.


Solution

  • You need to create a Service that is notified of the updates. Services run in the "background" even when your app is not running.

    This can get complicated since when a user is in your app, if you expect the app to update, then the activity will need to bind to the service.

    Here is a tutorial:

    http://www.vogella.com/tutorials/AndroidServices/article.html

    And the official docs are good too:

    http://developer.android.com/reference/android/app/Service.html

    Be careful - services can be shut down by Android when memory runs low. Users can also "force stop" your app. Don't assume that it is ALWAYS running, but you can assume it runs most of the time.

    And pay attention to the Service Lifecycle - it's different from and Activity:

    http://developer.android.com/guide/components/services.html#Lifecycle