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, mlocListen开发者_运维技巧er);
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
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);
Placing this in onPause() method will do the deactivation when leaving the Activity: mlocManager.removeUpdates(mlocListener);
If you have multiple Activities needing a gps listener I would go for the helper class in which I put the location manager and listener. There I would have public methods for initializing them and starting the listener, for getting the last known location and for deactivating the updates. Don't forget to add support for receiving the updates in your Activity.
Here's a good example:
Android find GPS location once, show loading dialog
精彩评论