如果最近打开了 LocationServices(GPS/WIFI/MOBILE DATA),则会调用超时,但会在一些延迟后开始工作。Google api 客户端被创建,连接时被调用,但它不返回任何位置。
以下代码用于 onConnected 并构建 google API:-
受保护的同步无效 buildGoogleApiClient() {
LogConfig.logd(TAG, "buildGoogleApiClient()");
if(mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
else
{
}
mGoogleApiClient.connect();
}
公共无效 onConnected(捆绑包){
LogConfig.logd(TAG,"onConnected");
//Check location permission if it is granted by user or not
int hasLocationAccessPermission = ContextCompat.checkSelfPermission(AnalyticsApplication.mContext, Manifest.permission.ACCESS_COARSE_LOCATION);
if (hasLocationAccessPermission == PackageManager.PERMISSION_GRANTED) {
if (mIsGetLastLocationRequest) {
mIsGetLastLocationRequest = false;
LogConfig.logd(TAG, "last Location Request");
try {
Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (loc != null) {
LogConfig.logd(TAG, "GotGPSFix:onConnected::" + loc.getLatitude() + "::" + loc.getLongitude());
updateLocation(loc);
} else {
if (mLocRequest == null) {
mLocRequest = new LocationRequest();
}
try {
mLocRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
gpsTimeoutValue = TIMEOUT_COARSE_LOCATION_FIX;
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocRequest, this);
startGpsTimeoutListener();
} catch (Exception exp) {
setChanged();
notifyObservers(LOCATION_RESULT_INVALID);
LogConfig.loge(TAG, "Exception: getLastLocation(): requestLocationUpdates" + exp);
}
}
} catch (Exception e) {
LogConfig.loge(TAG, "Exception: getLastLocation()" + e);
if (mLocRequest == null) {
mLocRequest = LocationRequest.create();
mLocRequest = new LocationRequest();
}
try {
mLocRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
gpsTimeoutValue = TIMEOUT_COARSE_LOCATION_FIX;
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocRequest, this);
startGpsTimeoutListener();
} catch (Exception exp) {
setChanged();
notifyObservers(LOCATION_RESULT_INVALID);
LogConfig.loge(TAG, "Exception: getLastLocation(): requestLocationUpdates" + exp);
}
}
} else {
LogConfig.logd(TAG, "Request for Fresh Location.");
try {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocRequest, this);
startGpsTimeoutListener();
} catch (Exception exp) {
setChanged();
notifyObservers(LOCATION_RESULT_TIMEOUT);
LogConfig.loge(TAG, "Exception: Request for Fresh Location" + exp);
}
}
}
}