I am trying to listen to location changes but sometimes onLocationChanged
callback is never called and getLastLocation
returns null
, w
First
It's kind of bug on old Android devices.
Apparently the location APIs have different behavior on different Android versions (LocationManager has issues on Android >= 4.1, while Play Services has issues on Android 2.3), see here.
So what I ended up with is below:
Trying to retrieve last location by play services, if failed try with LocationManager.
Second
I would like to thank you all for your valuable suggestions, I get the hint to use the previous workaround from AndroidHacker's post so I think he is the one who deserve the bounty.
From the doc, it's clear that it's sometime possible that the getLastLocation()
returns null. So, depending on what you mean by "I cannot receive onLocationChanged callbacks", you could just delay your startVisit
important calls (your toast display right now) until you have received this onLocationChanged callback. This way, if you have a direct access to the last known location, this will be direct, and otherwise you wait for the onLocationChanged callbacks
public class VisitService extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {
//...
boolean mIsInitialized=false;
Location mCurrentLocation;
boolean mStartVisitsCalled=false;
//...
public void startVisit() {
if (!servicesConnected()) {
listener.onVisitStartError();
return;
}
if (mLocationServiceConnected) {
if (((mLocationClient.getLastLocation() != null && isAcceptableLocation(mLocationClient.getLastLocation()))
|| (isInitialized && isAcceptableLocation(mCurrentLocation))) {
//doNiceStuff();
} else
mStartVisitsCalled=true;
//Wait...
}
}
}
//...
@Override
public void onLocationChanged(Location location) {
this.mIsInitialized=true;
this.mCurrrentLocation = location;
if(mStartVisitsCalled) {
//delayed doNiceStuff();
}
}
}