Search code examples
androidandroid-servicealarmmanagerlocationlistener

Android periodically get location and post to server using Service


I use a service class that implements LocationListener, to get the location at periodic intervals, and post to server at only when there is considerable change in the latlon(min 100 meters). Because, continuously updating server drains battery quickly. I start this service from onCreate() of myActivity, and don't call stopService() as it has to run forever.

When the user reboots the device, How to start the service again without opening the app? or

Is there any native or third party library to handle this part?


Solution

  • When the user reboots the device, How to start the service again without opening the app?

    you can implement receiver registered in the manifest which have intent filter to catch the [RECEIVE_BOOT_COMPLETED][1] broadcast. this requires also to add user permission: android.permission.RECEIVE_BOOT_COMPLETED

    see the example

    Is there any native or third party library to handle this part?

    there is the perfect third library called Google Play Services which is perfect for receiving location updates in background under all kind of available configurations. when requesting the right configuration (such accuracy/priority/interval) it's saving also lot's of battery. another great advantage - your app don't have to run at all in order to receive the location updates. instead, google play services will launch your service with the location object each time there will be update.

    see the example and documentation for more info

    note that either way you'll have to register to boot complete event as mentioned before, to re - register to location updates after boot complete.