tags:

views:

74

answers:

1

I implemented the GPS in my app, in one Activity like this:

 LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        LocationListener mlocListener = new MyLocationListener();
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

public class MyLocationListener implements LocationListener
    {
        public void onLocationChanged(Location location)
        {
            if (location != null) { //do something} 
        ...
        }

This is working fine. After evolving the app more I realized that I need to use the GPS in more than one activity. I need to be able to check if gps is active and what location does it return from 3 activities.

Imagine this scenario: the user starts the app. In background the GPS is trying to get satellite connection while the user selects some options. When I get to an activity that requires Location info I ask for it.

How can I achieve this ? Should this be running in another thread ? Please advise me. Thank you

+1  A: 

I've implemented it as an Android Service.

public class MyPositioningService extends Service {
  @Override
  public void onCreate() {
    // init LocationManager as you are doing
  }

  @Override
  public void onDestroy() {
    // LocationManager#removeUpdates
  }
}

You can start it when the user launches the application:

Intent i = new Intent(context, MyPositioningService.class);     
context.startService(i);
Guido
Thank you very much for help. And what tips can you offer regarding battery life? Needing the GPS only on certain screens, I need to be able to disable it in others. No ?
Alin
Good question. You can continously enable/disable it, but then you probably don't need a Service. Instead of that you can move your code to a helper class and call it from your 3 activities to get the current fix only when you need it. What you can do (if you go with the Service) to save battery life is to call requestLocationUpdates with minTime and minDistance arguments. That way you can get a fix i.e. only every 5 minutes.
Guido
I think I'll go then with a helper class. Could you provide some code sample like the one with service or guide me to a tutorial. I will try in meanwhile to do something. Thank you very much
Alin