I am working on Android application that has several threads – one of them is getting data from GPS receiver 1 time per second. I would like other threads to have access to information from the GPS thread.
I already tried doing it with message queues, but it made the code quite messy – all new threads I created had to handle messages in it’s own way, so I had to do a lot of new implementation in every thread class.
I would like to be able to simply get the data in this manner:
ApplicationState.getLocation();
so I can use the most recent data. How can I accomplish it? I don’t want to create static class with synchronized fields because I don’t want to lock the threads for too long because I am doing some online image analysis in other thread.
What approach would be the best here?
Cheers,
Nebril
Have you considered using an Event Bus system? Otto, an Apache licensed library from Square is pretty neat.
You could create a location updating class that fires new
LocationUpdateEvents. Any objects interested in receiving this update can have a method annotated with@Subscribe. It’s sweet method for interprocess communication that doesn’t rely on messy listener interfaces.Another advantage of Otto is that your LocationUpdater class could have a method annotated with @Produce. With this, any object that
beginslistening forLocationUpdateEventswill receive one immediately with the last location found by yourLocationUpdater.