问题
I am trying to write a location tracking service that starts as soon as the app is started, stops as soon as the app goes into the background, and restarts as soon as the app comes back to the foreground.
The service should poll for a new location every 5 minutes while it is running (to conserve battery) and when a new location is found (onLocationChanged()) it updates a variable that I can retrieve from any Activity.
I have tried binding a service in my custom Application class but the service never is bound before my initial Activity loads - and my initial Activity requires this service so I keep getting a null pointer exception when trying to access the service.
But maybe I am going in the wrong direction - what would be the best strategy for this? I don't need a super exact location and I don't care if it comes from the GPS or Network.
回答1:
below code worked for me...
you will get the location just use it wisely wherever you want...
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
来源:https://stackoverflow.com/questions/16144313/android-best-location-tracking-strategy