这是完全可行的解决方案,可能在略有不同的情况下。但我想添加一些小的解释步骤,以便任何人都能获得确切的概念。我没有看到您在代码中使用的 LocationEngine。在这里,我使用 LocationServices.FusedLocationApi 作为我的 LocationEngine。
1) Android 组件的 onCreate() (例如,Activity,Fragment或Service。注意:不是 IntentService),构建然后连接GoogleApiClient 如下。
buildGoogleApiClient();
mGoogleApiClient.connect();
其中, buildGoogleApiClient() 实现是,
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
稍后在 onDestroy() 上,您可以断开 GoogleApiClient 为,
@Override
public void onDestroy() {
Log.i(TAG, "Service destroyed!");
mGoogleApiClient.disconnect();
super.onDestroy();
}
第 1 步确保您构建并连接 GoogleApiClient。
1) GoogleApiClient 实例第一次通过 onConnected() 方法连接。现在,您的下一步应该查看 onConnected() 方法。
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i(TAG, "GoogleApiClient connected!");
buildLocationSettingsRequest();
createLocationRequest();
location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.i(TAG, " Location: " + location); //may return **null** because, I can't guarantee location has been changed immmediately
}
上面,您调用了方法createLocationRequest()来创建位置请求。方法createLocationRequest()如下所示。
protected void createLocationRequest() {
//remove location updates so that it resets
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); //Import should not be **android.Location.LocationListener**
//import should be **import com.google.android.gms.location.LocationListener**;
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//restart location updates with the new interval
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
3) 现在,在 LocationListener 接口的 onLocationChange() 回调中,您将获得新的位置。
@Override
public void onLocationChanged(Location location) {
Log.i(TAG, "Location Changed!");
Log.i(TAG, " Location: " + location); //I guarantee,I get the changed location here
}
你在 Logcat 中得到这样的结果:
03-22 18:34:17.336 817-817/com.LiveEarthquakesAlerts I/LocationTracker: Location: Location[fused 37.421998,-122.084000 acc=20 et=+15m35s840ms alt=0.0]
为了能够完成这三个步骤,您应该如下配置您的 build.gradle:
compile 'com.google.android.gms:play-services-location:10.2.1'