Details
The app has a background service running when the app is started. In this service, on onStartCommand() starts listening for GPS location with a parameter for passed meters between reads. Let’s say 50 meters for example. Each time a location is read the following operations occur:
- read location is stored in a local database
- retrieve all unsent location from the database
- location(s) is sent to a web server
- if sending is successful, the location(s) is deleted from the database
Now this behavior happens every time a location is read.The user might be walking which takes some time to make the 50 meters or drive fast, while many reads can be done and things might get messy in the database insert/retrieve. So one of the main requests is to have all read locations processed sequentially, as they were read. Something like: read location 1, insert it, send it… read location 2, insert it, send it.
I can’t find out a proper way to do this. As you know, the service runs in the same main thread as the app, so I definitely need to use threading to keep the UI running smooth.
I was thinking to use ExecutorService and a Executors.newSingleThreadExecutor() to which to submit new threads each time a location is read. In this way, I make sure processing is done in sequence but… I make new threads for each read, which might not be such a good thing.
What best approach would you suggest for this situation ?
What I would do is remove the service and throw an IntentService every time a location is read.
You can use requestLocationUpdates with pending intent argument, and set the pending intent argument with an intent that triggers your intent service.
In the intentservice’s onHandleIntent you can then handle the location update. Intents are handled sequentially by intent service, and it handles them in a separate thread (and then expires).
If you just need to consume one shot events on background, intentservice are a more compact and suitable solution.