2014-04-07 11 views
17

Wenn ich diese beiden Geofences habe, sollte ich nach dem Registrieren dieser Geofences benachrichtigt werden, wenn ich den Umfang dieser Kreise betrete oder verlasse. Ich möchte jedoch nicht, dass meine App eine Benachrichtigung sendet, wenn ich mich durch den allgemeinen Bereich bewege, also von einem Kreis zum nächsten.Umgang mit mehreren Geofences Übergang mit gemeinsamen Bereich

Ist es möglich? Wenn ja, wie?

Image of map with two circles intersecting

+0

Ja, das ist sehr viel möglich, jetzt müssen Sie die Union hier anwenden, um die gemeinsamen Orte und die bekannten Stellen unter dem Umfang zu erhalten und die gemeinsamen Orte von zwei Umfang zu unterteilen. Jetzt können Sie den Abstand vom Mittelpunkt verwenden und die Abstandsformel anwenden. –

+0

können Sie Ihre Antwort ein wenig mehr.than @jitainsharma – Pankaj

Antwort

13

Sie erhalten eine class zur Überwachung der Umzäunung verwenden müssen:

public class GeofenceReceiver extends BroadcastReceiver { 
    Context context; 

    Intent broadcastIntent = new Intent(); 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     this.context = context; 

     broadcastIntent.addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES); 

     if (LocationClient.hasError(intent)) { 
      handleError(intent); 
     } else { 
      handleEnterExit(intent); 
     } 
    } 

    private void handleError(Intent intent){ 
     // Get the error code 
     int errorCode = LocationClient.getErrorCode(intent); 

     // Get the error message 
     String errorMessage = LocationServiceErrorMessages.getErrorString(
       context, errorCode); 

     // Log the error 
     Log.e(GeofenceUtils.APPTAG, 
       context.getString(R.string.geofence_transition_error_detail, 
         errorMessage)); 

     // Set the action and error message for the broadcast intent 
     broadcastIntent 
       .setAction(GeofenceUtils.ACTION_GEOFENCE_ERROR) 
       .putExtra(GeofenceUtils.EXTRA_GEOFENCE_STATUS, errorMessage); 

     // Broadcast the error *locally* to other components in this app 
     LocalBroadcastManager.getInstance(context).sendBroadcast(
       broadcastIntent); 
    } 


    private void handleEnterExit(Intent intent) { 
     // Get the type of transition (entry or exit) 
     int transition = LocationClient.getGeofenceTransition(intent); 

     // Test that a valid transition was reported 
     if ((transition == Geofence.GEOFENCE_TRANSITION_ENTER) 
       || (transition == Geofence.GEOFENCE_TRANSITION_EXIT)) { 

      // Post a notification 
      List<Geofence> geofences = LocationClient 
        .getTriggeringGeofences(intent); 
      String[] geofenceIds = new String[geofences.size()]; 
      String ids = TextUtils.join(GeofenceUtils.GEOFENCE_ID_DELIMITER, 
        geofenceIds); 
      String transitionType = GeofenceUtils 
        .getTransitionString(transition); 

      for (int index = 0; index < geofences.size(); index++) { 
       Geofence geofence = geofences.get(index); 
       ...do something with the geofence entry or exit. I'm saving them to a local sqlite db 

      } 
      // Create an Intent to broadcast to the app 
      broadcastIntent 
        .setAction(GeofenceUtils.ACTION_GEOFENCE_TRANSITION) 
        .addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES) 
        .putExtra(GeofenceUtils.EXTRA_GEOFENCE_ID, geofenceIds) 
        .putExtra(GeofenceUtils.EXTRA_GEOFENCE_TRANSITION_TYPE, 
          transitionType); 

      LocalBroadcastManager.getInstance(MyApplication.getContext()) 
        .sendBroadcast(broadcastIntent); 

      // Log the transition type and a message 
      Log.d(GeofenceUtils.APPTAG, transitionType + ": " + ids); 
      Log.d(GeofenceUtils.APPTAG, 
        context.getString(R.string.geofence_transition_notification_text)); 

      // In debug mode, log the result 
      Log.d(GeofenceUtils.APPTAG, "transition"); 

      // An invalid transition was reported 
     } else { 
      // Always log as an error 
      Log.e(GeofenceUtils.APPTAG, 
        context.getString(R.string.geofence_transition_invalid_type, 
          transition)); 
     } 
    } 

    //Posts a notification in the notification bar when a transition 
    private void sendNotification(String transitionType, String locationName) { 

     // Create an explicit content Intent that starts the main Activity 
     Intent notificationIntent = new Intent(context, MainActivity.class); 

     // Construct a task stack 
     TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); 

     // Adds the main Activity to the task stack as the parent 
     stackBuilder.addParentStack(MainActivity.class); 

     // Push the content Intent onto the stack 
     stackBuilder.addNextIntent(notificationIntent); 

     // Get a PendingIntent containing the entire back stack 
     PendingIntent notificationPendingIntent = stackBuilder 
       .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 

     // Get a notification builder that's compatible with platform versions 
     // >= 4 
     NotificationCompat.Builder builder = new NotificationCompat.Builder(
       context); 

     // Set the notification contents 
     builder.setSmallIcon(R.drawable.ic_notification) 
       .setContentTitle(transitionType + ": " + locationName) 
       .setContentText(
         context.getString(R.string.geofence_transition_notification_text)) 
       .setContentIntent(notificationPendingIntent); 

     // Get an instance of the Notification manager 
     NotificationManager mNotificationManager = (NotificationManager) context 
       .getSystemService(Context.NOTIFICATION_SERVICE); 

     // Issue the notification 
     mNotificationManager.notify(0, builder.build()); 
    } 

Sie sollten Sie für jeden der Bereiche Zuhörer erstellen möchten zu überwachen, sagen wir listen1 und listener2. Um beide Bereiche zu optimieren und zu integrieren, ist es am besten, ein Gitter mit MongoDB zu erstellen, mit dem Sie sogar mehr als zwei Punkte integrieren können, wenn Sie ein Gitter erstellen.

enter image description here

Unter der Annahme, dass Sie ein Polygon in Form einiger Lat-Lon Punkte raus gehen, dann können Sie ein grid wie die folgenden erzeugen:

# Method to get the min and max values for the polygon 
def get_bounding_box(coords) 
# get max and min coords 
max = coords.inject({lat:0, lon:0}) do |max, c| 
max[:lon] = c[0] if c[0] > max[:lon] 
max[:lat] = c[1] if c[1] > max[:lat] 
max 
end 
min = coords.inject({lat:MAX_LAT, lon:MAX_LON}) do |min, c| 
min[:lon] = c[0] if c[0] < min[:lon] 
min[:lat] = c[1] if c[1] < min[:lat] 
min 
end 
# add a little padding to the max and min 
max.each {|k, v| max[k] += 1 } 
min.each {|k, v| min[k] -= 1 } 

{min: min, max: max} 
end 

def generate_grid(bounds) 
lon_range = bounds[:min][:lon]...bounds[:max][:lon] 
lat_range = bounds[:min][:lat]...bounds[:max][:lat] 

grid = [] 
lon_range.each do |lon| 
lat_range.each do |lat| 
grid << [lon + 0.25, lat + 0.25] 
grid << [lon + 0.25, lat + 0.75] 
grid << [lon + 0.75, lat + 0.25] 
grid << [lon + 0.75, lat + 0.75] 
end 
end 

grid 
end 

Ein solcher Ansatz erlaubt

enter image description here

: Sie very efficient Geofencing mit Smart Grids für die Überwachung der Zielbereiche zu erreichen

Kürzlich MongoDB auch Unterstützung für Android hinzugefügt, so bietet eine einfache Möglichkeit für Ihre Android App Back-End-Integration. In der Tat wird erwartet, dass die Geofencing-Entwicklung mit intelligenten verteilten Daten eine wachsende Zahl von applications haben wird.

0

sehr schematisch:

boolean isTransition1, isTransition2, isTransition, insideCircle1, insideCircle2, insideUnion, insideUnionPrev; 

if (isTransition1 | isTransition2) { 
    insideCircle1 = (dist(currPosition, centerCircle1) < radius1); 
    insideCircle2 = (dist(currPosition, centerCircle2) < radius2); 
    insideUnionPrev = insideUnion; 
    insideUnion = insideCircle1 | insideCircle; 
    isTransition = (insideUnion != insideUnionPrev); 
    if (isTransition & insideUnion) println("Moved into region"); 
    if (isTransition & !insideUnion) println("Moved out of region"); 
} 
+0

Ich denke, es wird nicht funktionieren für Android Geofence, durch die Dank für die Hilfe – Pankaj

+0

Warum denkst du nicht, es wird funktionieren? Es ist einfache Logik, verwenden Sie einfach den Rückruf, um die iTransition1,2 bools ... – user1939887

1

Dies kann eine Alternative sein:

Alle geofences haben eine id; Ich bin mir nicht sicher, dass sie einzigartig sein müssen, aber für diese Diskussion müssen wir sagen, dass sie einzigartig sein müssen. Verwenden Sie in Ihren beiden Geofence-Beispielen die IDs "fenceHome-1" und "fenceHome-2" für die gezeigten und eine dritte namens "someOther-1", die nicht angezeigt wird.

Jetzt können Sie eine Variable erstellen, um den aktuellen Geofence zu speichern, in dem sich der Benutzer befindet. In diesem Beispiel wird es eine Zeichenfolge mit der Geofence-ID sein. Nennen wir es

String currentGeofence = new String(); 

Wenn der Benutzer ein neues Geofence betritt können Sie nun überprüfen, ob die geofenceIds gleich sind.

 /** 
     geofenceEntered get from the Intent. Should be "fenceHome-1" or "fenceHome-2" or "someOther=1" 
     */  
    public void enteredGeoFence(String geofenceEntered) { 

     // strip off the "-1" or "-2" 
     geofenceEntered = geofenceEntered.stripOff(); 

     if (currentGoofence.equals(geofenceEntered) == false} { 
      // user entered a new geofence Ex: "SomeOther-1" to "fenceHome-1" 
      sendNotification(geofenceEntered, .....); 
      currentGeofence = geofencecEntered; 
     } else { 
      // user entered a geofence with in the same 'area'. Ex: "fenceHome-1" to "fenceHome-2" 
      // do nothing 
     } 

    } 

So würde ich es machen. Mit all der Mathematik zu hantieren ist viel zu schwer. Setzen Sie einfach eine clevere Namenskonvention für Ihre Geofence-IDs. Der Schlüssel ist die Benennung der Geofences.

In der realen Welt müsste currentGeofence eine Sammlung sein, da ein Benutzer in mehreren Geofences sein könnte und das geofenceExit() aus currentGeofence entfernen müsste.

Noch eine Erinnerung an den Android Notification Manager: Wenn Sie dieselbe Benachrichtigung zweimal senden, wird nur eine Benachrichtigung gesendet. Dies könnte zu Ihrem Vorteil genutzt werden.

+0

können Sie bitte Ihren Code ...? –

Verwandte Themen