Android地理围栏无法使用动态地理围栏加载(排球请求)

时间:2015-04-17 10:59:53

标签: android google-play-services android-geofence

我试图从api动态加载地理围栏,但我遇到了问题。 当我将静态数据加载到我的应用程序中时(例如硬编码)一切顺利(地理围栏快速触发)但是如果我尝试从远程服务器加载数据,则地理围栏操作不会再触发。我用Volley来处理请求。

onCreate方法

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    // Empty list for storing geofences.
    mGeofenceList = new ArrayList<Geofence>();

    // Initially set the PendingIntent used in addGeofences() and removeGeofences() to null.
    mGeofencePendingIntent = null;

    geofencePointsRequest(this, null, null);

    buildGoogleApiClient();
}

排球请求检索数据

public void geofencePointsRequest(final Context context, Map<String,String> params, final ProgressDialog pDialog){
    webService = new WebService();

    CustomArrayRequest jsonObjReq = new CustomArrayRequest(
            Request.Method.GET,
            WebServiceUrl.POINTS,
            params,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    ArrayList<Point> points = webService.getPoints(response);
                    populateGeofenceList(points);
                }
            },

            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    String errorHandler = webService.getError(error);
                    int status = (error.networkResponse.statusCode != 0) ? error.networkResponse.statusCode : 0;
                    Toast.makeText(context, "Code : " + status + " - Error : " + errorHandler, Toast.LENGTH_LONG).show();
                }
            }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return webService.getHeaders();
        }
    };

    VolleySingleton.getInstance(context).addToRequestQueue("pointsRequest", jsonObjReq);
}

构建GoogleApiClient

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

在连接时我加载地理围栏

@Override
public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "Connected to GoogleApiClient");
    addGeofencesOnLoad();
}

private GeofencingRequest getGeofencingRequest() {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
    builder.addGeofences(mGeofenceList);
    return builder.build();
}

public void addGeofencesOnLoad() {
    if (!mGoogleApiClient.isConnected()) {
        Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
        return;
    }

    try {
        LocationServices.GeofencingApi.addGeofences(
                mGoogleApiClient,
                getGeofencingRequest(),
                getGeofencePendingIntent()
        ).setResultCallback(this); // Result processed in onResult().
    } catch (SecurityException securityException) {
        logSecurityException(securityException);
    }
}

我创建了一个地理围栏列表(来自解析的数据)

public void populateGeofenceList(ArrayList<Point> points) {
    for (int i=0; i<points.size(); i++) {
        mGeofenceList.add(new Geofence.Builder()
                .setRequestId(pins.get(i).getShortId())
                .setCircularRegion(
                        points.get(i).getLocation().getCoordinates().latitude,
                        points.get(i).getLocation().getCoordinates().longitude,
                        points.get(i).getLocation().getRadius()
                )
                .setExpirationDuration(Geofence.NEVER_EXPIRE)
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
                .build());
    }
}
编辑:我在代码中重构了buildGoogleApiClient位置,但问题始终是它没有触发通知...

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您似乎没有初始化Google Api客户端, buildGoogleApiClient()方法在 populateGeofenceList 被调用之前不会执行,如果您没有连接到Google Api客户端。

因此,您的问题可能是Google Api客户端为空,因此无法连接。点击这里:

 protected void onStart() {
    super.onStart();
    if (mGoogleApiClient != null) mGoogleApiClient.connect();
}