Reputation: 3273
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
Upvotes: 2
Views: 487
Reputation: 2004
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 begins
listening for LocationUpdateEvents
will receive one immediately with the last location found by your LocationUpdater
.
Upvotes: 3
Reputation: 3322
1)create your application class "MyApp" :
1.1)in the manifest file:
<application
android:name=".MyApp"
....
/>
1.2)create the class:
public class MyApp extends Application {
public void onCreate() {
super.onCreate();
}
private volatile Location mLastLocation = null;
public Location getLastLocation(){
return mLastLocation;
}
public void setLastLocation(Location mLastLocation){
this.mLastLocation = mLastLocation;
}
}
2)to set the location from any context in your application (services, any activities) in the same process (be careful to have one process. You can have 1 process and multi thread in android) :
((MyApp)context.getApplicationContext()).setLastLocation(location);
3)to get the latest location from any context in your application in the same process:
((MyApp)context.getApplicationContext()).getLastLocation();
NB: you can also use listeners for better performance. Register in a list in MyApp listeners and trigger the listeners from onLocationChanged
Upvotes: 1