Reputation: 2213
Hi I have a service running and fetch location every 30 seconds (as it showns in code(1)) I want to store location to be available at anytime my aproach is to store as a global variable within the application context (as it showns in code(2) and code(1)) so, later I can get it from MainActivity as shown in code(3).
code (1)
public class LocationService extends Service{
@Override
public void onCreate(){
// I have a service here from where I can get Location every 30 secs
{
Location location=// from android api get Location every 30 secs
((App)getApplication()).setLocation(location);
}
}
}
(2)
public class App extends Application{
Location mLocation;
public void setLocation(Location location){
mLocation=location;
}
public Location getLocation(){
return mLocation;
}
(3)
public class MainActivity extends Activity{
@Override
public void onCreate(){
Location location=((App)getApplication()).getLocation();
}
}
My Question is that aproach valid?. I saw that usually is used either broadcast or bind service and activity, I have never seen to share gloabal variable between service and activity, ¿why?.
Any discussion is wellcome.
Upvotes: 1
Views: 78
Reputation: 2669
You approach is a valid one. according to the android developer site you have the following options:
Each one of these approaches depends on the situation. In my opinion it is better to store the location in a static field, and expose a static getter method for that field in your Service.
Upvotes: 1