【发布时间】:2017-02-23 10:45:26
【问题描述】:
我正在尝试使用从外部 API 加载的地理围栏位置创建一个 Android 应用程序。我使用改造来进行 aysnc 调用。问题是googleApiClient 和外部 API 调用都是异步的。所以我不知道哪个先完成才能启动地理围栏。
如果我在googleApiClient 的onConnected() 中启动地理围栏,我可能还没有来自API 的LatLng。但如果我从 API 的回调中启动地理围栏,googleApiClient 可能尚未加载。
除了在googleApiClient 的onConnected() 中进行异步 API 调用之外,我还能做些什么来处理这个问题。我试图避免多个回调级别。这是我目前不起作用的代码,因为我认为调用 startGeofences() 时 API 的结果还不存在:
public class GeofenceHelper implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener, ResultCallback<Status> {
private List<Geofence> mGeofenceList = new ArrayList<>();
private GoogleApiClient googleApiClient;
public GeofenceHelper(Activity context){
this.context = context;
permissionsHelper = new PermissionsHelper(context, REQ_PERMISSION);
buildGoogleApiClient();
geofencePointsRequest();
}
private void startGeofences() {
Log.i(TAG, "startGeofences()");
if (!googleApiClient.isConnected()) {
Log.d(TAG, "Not connected");
return;
}
if (permissionsHelper.checkPermission())
LocationServices.GeofencingApi.addGeofences(
googleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(this); // Result processed in onResult()
}
private void geofencePointsRequest() {
GeofenceAreasRequest response = new GeofenceAreasRequest();
response.getAllAreas(new GeofenceAreasResponse() {
@Override
public void onAreasLoaded(List<Point> points, int code) {
Log.i(TAG, "Responsecode: " + String.valueOf(code));
for (int i = 0; i < points.size(); i++) {
mGeofenceList.add(new Geofence.Builder()
.setRequestId(points.get(i).getName())
.setCircularRegion(
points.get(i).getLatitude(),
points.get(i).getLongitude(),
points.get(i).getRadius())
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER
| Geofence.GEOFENCE_TRANSITION_EXIT)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build());
}
}
});
}
private GeofencingRequest getGeofencingRequest() {
Log.d(TAG, "getGeofencingRequest");
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}
public void start(){
googleApiClient.connect();
}
public void stop(){
googleApiClient.disconnect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i(TAG, "google api connected");
startGeofences();
getLastKnownLocation();
}
}
【问题讨论】:
-
尝试改造aysnc调用onConnected()方法,当你得到你的调用响应时调用startGeofences()。
-
您能详细说明一下吗?因为这不是我在原始帖子中解释的试图避免做的事情吗?
标签: android api asynchronous google-api geofencing