Play Location Services getLastLocation returns null

前端 未结 8 1756
感动是毒
感动是毒 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: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();
            }
    
        }
    }
    

提交回复
热议问题