Play Location Services getLastLocation returns null

前端 未结 8 1758
感动是毒
感动是毒 2021-01-13 13:51

I am trying to listen to location changes but sometimes onLocationChanged callback is never called and getLastLocation returns null, w

相关标签:
8条回答
  • 2021-01-13 14:06

    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.

    0 讨论(0)
  • 2021-01-13 14:09

    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();
            }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题