in my App I have a GpsStatus.Listener to receive events when the user enables or disables GPS. Everything works fine if GPS is on before I start the app. In this case I receive a GPS_EVENT_STARTED or a GPS_EVENT_STOPPED everytime I toggle GPS on or off.
The problem is if GPS is off while app is starting. In this case I don't receive an event if I toggle GPS on or off.
Can someone explain that to me?
Here is my code:
public class GPSTracker implements android.location.GpsStatus.Listener {
private final Context context;
private final LocationListener locListener;
private LocationManager locationManager;
private boolean isGPSEnabled = false;
public GPSTracker(Context context, LocationListener locListener) {
this.context = context;
this.locListener = locListener;
setupGPS();
}
private void setupGPS() {
locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.addGpsStatusListener(this);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!isGPSEnabled) {
Toast.makeText(getContext(), "GPS disabled", Toast.LENGTH_SHORT).show();
} else {
locationManager.removeUpdates(locListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, locListener);
}
}
@Override
public void onGpsStatusChanged(int event) {
Log.e("onGpsStatusChanged", event+"");
switch(event) {
case GpsStatus.GPS_EVENT_STARTED:
Log.e("onGpsStatusChanged", "GPS_EVENT_STARTED");
break;
case GpsStatus.GPS_EVENT_STOPPED:
Log.e("onGpsStatusChanged", "GPS_EVENT_STOPPED");
break;
}
}
So, my logcat output is (if GPS is on while starting):
- GpsStatusChanged(24638): 1 // app starts
- GpsStatusChanged(24638): GPS_EVENT_STARTED
- GpsStatusChanged(24638): 4 // searching for fixes
- GpsStatusChanged(24638): 4
- GpsStatusChanged(24638): 2 // toggle GPS off
- GpsStatusChanged(24638): GPS_EVENT_STOPED
Output with GPS off: nothing.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…