2014-04-13 43 views
3

我在我的應用程序中使用地理柵欄,除了刪除觸發的地理柵欄之外,一切正常。 我從Android的官方文檔中獲取紅色指南,但他們沒有解釋如何去除IntentService中的地理圍欄。觸發後刪除地理柵欄

這裏是服務的事件處理程序的代碼:

@Override 
protected void onHandleIntent(Intent intent) 
{ 
    Log.e("GeofenceIntentService", "Location handled"); 

    if (LocationClient.hasError(intent)) 
    { 
     int errorCode = LocationClient.getErrorCode(intent); 
     Log.e("GeofenceIntentService", "Location Services error: " + Integer.toString(errorCode)); 
    } 
    else 
    { 
     int transitionType = LocationClient.getGeofenceTransition(intent); 
     if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER) 
     { 
      List <Geofence> triggerList = LocationClient.getTriggeringGeofences(intent); 
      String[] triggerIds = new String[triggerList.size()]; 

      for (int i = 0; i < triggerIds.length; i++) 
      { 
       // Store the Id of each geofence 
       triggerIds[i] = triggerList.get(i).getRequestId(); 

       Picture p = PicturesManager.getById(triggerIds[i], getApplicationContext()); 
        /* ... do a lot of work here ... */ 


      } 

     } 
     else 
      Log.e("ReceiveTransitionsIntentService", "Geofence transition error: " + Integer.toString(transitionType)); 
    } 
} 

如何刪除地理圍欄他得到觸發後?

回答

1

您將按照添加地理柵欄時所做的操作(創建LocationClient並等待它連接)。在連接後,使用onConnected回撥方法,您可以在LocationClient實例上調用removeGeofences,然後將其傳遞給您要刪除的請求ID列表,並將OnRemoveGeofencesResultListener的實例作爲回調處理程序傳遞給它。

當然,您必須使用與創建GeoFence時使用的請求ID相同的GeoFence.BuildersetRequestId

@Override 
public void onConnected(Bundle arg0) { 
    locationClient.removeGeofences(requestIDsList, 
    new OnRemoveGeofencesResultListener() { 
    ...  
}); 
+0

所以我創建的服務LocationClient? – Gp2mv3

+0

我不知道,添加Geofences時,你在哪裏創建它? – Jeshurun

+2

LocationClient不再包含在播放服務中。 – mrroboaat

2

你可以做這樣的事情:

LocationServices.GeofencingApi.removeGeofences(
      mGoogleApiClient, 
      // This is the same pending intent that was used in addGeofences(). 
      getGeofencePendingIntent() 
).setResultCallback(this); // Result processed in onResult(). 

而且你getGeofencePendingIntent()方法可以是這樣的:

/** 
* Gets a PendingIntent to send with the request to add or remove Geofences. Location Services 
* issues the Intent inside this PendingIntent whenever a geofence transition occurs for the 
* current list of geofences. 
* 
* @return A PendingIntent for the IntentService that handles geofence transitions. 
*/ 
private PendingIntent getGeofencePendingIntent() { 
    Log.d(TAG, "getGeofencePendingIntent()"); 
    // Reuse the PendingIntent if we already have it. 
    if (mGeofencePendingIntent != null) { 
     return mGeofencePendingIntent; 
    } 
    Intent intent = new Intent(mContext, GeofenceIntentServiceStub.class); 
    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling 
    // addGeofences() and removeGeofences(). 
    mGeofencePendingIntent = PendingIntent.getService(mContext, 0, intent, 
      PendingIntent.FLAG_UPDATE_CURRENT); 
    return mGeofencePendingIntent; 
}