问题
I'm trying to have a background gps location listener as a service that can be used by all activities in my app. It should also be scanning for locations until I "kill" it. However I realized that after a couple of hours the gps service gets killed and I can't get anymore locations.
How do I keep this service alive (the locationManager and location listener at least) until I want it off?
Thanks
public class GPS extends IntentService {
public static LocationListener loc_listener = null;
public static LocationManager locationManager = null;
public GPS() {
super("GPS");
}
@Override
protected void onHandleIntent(Intent intent) {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (loc_listener == null) {
loc_listener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
};
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, loc_listener);
}
public static void killGPS() {
if (locationManager != null && loc_listener != null) {
locationManager.removeUpdates(loc_listener);
}
}
}
回答1:
However I realized that after a couple of hours the gps service gets killed and I can't get anymore locations.
First, it is an exceptionally bad idea to keep GPS powered on all of the time, as the user's battery life will suffer greatly. Your application needs to offer tremendous value (e.g., Google Navigation) to warrant this power cost.
Second, never register a listener from an IntentService
. Once onHandleIntent()
ends, the service shuts down... but you leak your registered listener. This effectively keeps a background thread going. However, since you have no active components, Android eventually will terminate your process.
来源:https://stackoverflow.com/questions/7694381/how-to-keep-background-gps-service-alive