com.google.android.gms.location.Geofence Java Examples

The following examples show how to use com.google.android.gms.location.Geofence. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GeofenceTransitionsIntentService.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
private String getGeofenceTransitionDetails(
        Context context,
        int geofenceTransition,
        List<Geofence> triggeringGeofences) {

    String geofenceTransitionString = getTransitionString(geofenceTransition);

    // Get the Ids of each geofence that was triggered.
    ArrayList triggeringGeofencesIdsList = new ArrayList();
    for (Geofence geofence : triggeringGeofences) {
        triggeringGeofencesIdsList.add(geofence.getRequestId());
    }
    String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);

    return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
}
 
Example #2
Source File: LocationManagerImplementation.java    From Leanplum-Android-SDK with Apache License 2.0 6 votes vote down vote up
private Geofence geofenceFromMap(Map<String, Object> regionData, String regionName) {
  Number latitude = (Number) regionData.get("lat");
  Number longitude = (Number) regionData.get("lon");
  Number radius = (Number) regionData.get("radius");
  Number version = (Number) regionData.get("version");
  if (latitude == null) {
    return null;
  }
  Builder geofenceBuilder = new Builder();
  geofenceBuilder.setCircularRegion(latitude.floatValue(),
      longitude.floatValue(), radius.floatValue());
  geofenceBuilder.setRequestId(geofenceID(regionName, version.intValue()));
  geofenceBuilder.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
      Geofence.GEOFENCE_TRANSITION_EXIT);
  geofenceBuilder.setExpirationDuration(Geofence.NEVER_EXPIRE);
  return geofenceBuilder.build();
}
 
Example #3
Source File: MainActivity.java    From AndroidWearable-Samples with Apache License 2.0 6 votes vote down vote up
/**
 * In this sample, the geofences are predetermined and are hard-coded here. A real app might
 * dynamically create geofences based on the user's location.
 */
public void createGeofences() {
    // Create internal "flattened" objects containing the geofence data.
    mAndroidBuildingGeofence = new SimpleGeofence(
            ANDROID_BUILDING_ID,                // geofenceId.
            ANDROID_BUILDING_LATITUDE,
            ANDROID_BUILDING_LONGITUDE,
            ANDROID_BUILDING_RADIUS_METERS,
            GEOFENCE_EXPIRATION_TIME,
            Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT
    );
    mYerbaBuenaGeofence = new SimpleGeofence(
            YERBA_BUENA_ID,                // geofenceId.
            YERBA_BUENA_LATITUDE,
            YERBA_BUENA_LONGITUDE,
            YERBA_BUENA_RADIUS_METERS,
            GEOFENCE_EXPIRATION_TIME,
            Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT
    );

    // Store these flat versions in SharedPreferences and add them to the geofence list.
    mGeofenceStorage.setGeofence(ANDROID_BUILDING_ID, mAndroidBuildingGeofence);
    mGeofenceStorage.setGeofence(YERBA_BUENA_ID, mYerbaBuenaGeofence);
    mGeofenceList.add(mAndroidBuildingGeofence.toGeofence());
    mGeofenceList.add(mYerbaBuenaGeofence.toGeofence());
}
 
Example #4
Source File: GeofenceTransitionsJobIntentService.java    From location-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Gets transition details and returns them as a formatted string.
 *
 * @param geofenceTransition    The ID of the geofence transition.
 * @param triggeringGeofences   The geofence(s) triggered.
 * @return                      The transition details formatted as String.
 */
private String getGeofenceTransitionDetails(
        int geofenceTransition,
        List<Geofence> triggeringGeofences) {

    String geofenceTransitionString = getTransitionString(geofenceTransition);

    // Get the Ids of each geofence that was triggered.
    ArrayList<String> triggeringGeofencesIdsList = new ArrayList<>();
    for (Geofence geofence : triggeringGeofences) {
        triggeringGeofencesIdsList.add(geofence.getRequestId());
    }
    String triggeringGeofencesIdsString = TextUtils.join(", ",  triggeringGeofencesIdsList);

    return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
}
 
Example #5
Source File: GeofenceBroadcastReceiver.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
  GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);

  if (geofencingEvent.hasError()) {
    int errorCode = geofencingEvent.getErrorCode();
    String errorMessage = GeofenceStatusCodes.getStatusCodeString(errorCode);
    Log.e(TAG, errorMessage);
  } else {
    // Get the transition type.
    int geofenceTransition = geofencingEvent.getGeofenceTransition();

    // A single event can trigger multiple geofences.
    // Get the geofences that were triggered.
    List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

    // TODO React to the Geofence(s) transition(s).
  }
}
 
Example #6
Source File: GeofenceData.java    From android-sdk with MIT License 6 votes vote down vote up
protected static List<GeofenceData> from(GeofencingEvent event) {
    String problem = check(event);
    if (problem != null) {
        throw new IllegalArgumentException(problem);
    }
    ArrayList<GeofenceData> result = new ArrayList<>();
    for (Geofence geofence : event.getTriggeringGeofences()) {
        try {
            result.add(new GeofenceData(geofence.getRequestId()));
        } catch (IllegalArgumentException ex) {
            Logger.log.logError(ex.getMessage());
        }
    }
    if (result.isEmpty()) {
        throw new IllegalArgumentException("GeofencingEvent has no triggering geofences");
    }
    return result;
}
 
Example #7
Source File: GeofenceData.java    From android-sdk with MIT License 6 votes vote down vote up
private static String check(GeofencingEvent event) {
    if (event == null) {
        return "GeofencingEvent is null";
    }
    if (event.hasError()) {
        return "GeofencingEvent has error: "+event.getErrorCode();
    }
    if (event.getTriggeringGeofences() == null) {
        return "GeofencingEvent has no triggering geofences";
    }
    if (event.getTriggeringGeofences().isEmpty()) {
        return "GeofencingEvent has empty list of triggering geofences";
    }
    int transition = event.getGeofenceTransition();
    //Only GEOFENCE_TRANSITION_ENTER and GEOFENCE_TRANSITION_EXIT are supported for now.
    if (transition != Geofence.GEOFENCE_TRANSITION_ENTER && transition != Geofence.GEOFENCE_TRANSITION_EXIT) {
        return "GeofencingEvent has invalid transition: "+transition;
    }
    return null;
}
 
Example #8
Source File: GeofenceStorage.java    From android-sdk with MIT License 6 votes vote down vote up
private HashMap<String, Geofence> getGeofencesFromCursor(Cursor cursor, int limit) {
    HashMap<String, Geofence> result = new HashMap<>(limit);
    Geofence geofence;
    int i = 0;
    while (cursor.moveToNext()) {
        i++;
        if (i <= HIGH) {
            String fence = cursor.getString(cursor.getColumnIndex(DBHelper.TG_FENCE));
            geofence = buildGeofence(fence);
            if (geofence != null) {
                result.put(fence, geofence);
            }
        } else {
            Logger.log.geofenceError("Over " + HIGH + " found in cursor", null);
            break;
        }
    }
    return result;
}
 
Example #9
Source File: GeofenceStorage.java    From android-sdk with MIT License 6 votes vote down vote up
private Geofence buildGeofence(String fence) {
    try {
        GeofenceData temp = new GeofenceData(fence);
        return new Geofence.Builder()
                .setRequestId(temp.getFence())
                .setCircularRegion(
                        temp.getLatitude(),
                        temp.getLongitude(),
                        temp.getRadius())
                .setExpirationDuration(Long.MAX_VALUE)
                .setNotificationResponsiveness(settings.getGeofenceNotificationResponsiveness())
                //TODO this could be optimized to trigger only on entry / exit according to layout. Not worth it now.
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                .build();
    } catch (IllegalArgumentException ex) {
        Logger.log.geofenceError("Invalid geofence: "+fence, ex);
        return null;
    }
}
 
Example #10
Source File: GeofencingService.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
@Override
protected void onHandleIntent( Intent intent ) {
	NotificationCompat.Builder builder = new NotificationCompat.Builder( this );
	builder.setSmallIcon( R.drawable.ic_launcher );
	builder.setDefaults( Notification.DEFAULT_ALL );
	builder.setOngoing( true );

	int transitionType = LocationClient.getGeofenceTransition( intent );
	if( transitionType == Geofence.GEOFENCE_TRANSITION_ENTER ) {
		builder.setContentTitle( "Geofence Transition" );
		builder.setContentText( "Entering Geofence" );
		mNotificationManager.notify( 1, builder.build() );
	}
	else if( transitionType == Geofence.GEOFENCE_TRANSITION_EXIT ) {
		builder.setContentTitle( "Geofence Transition" );
		builder.setContentText( "Exiting Geofence" );
		mNotificationManager.notify( 1, builder.build() );
	}
}
 
Example #11
Source File: MainActivity.java    From AndroidWearable-Samples with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Rather than displayng this activity, simply display a toast indicating that the geofence
    // service is being created. This should happen in less than a second.
    Toast.makeText(this, getString(R.string.start_geofence_service), Toast.LENGTH_SHORT).show();

    // Instantiate a new geofence storage area.
    mGeofenceStorage = new SimpleGeofenceStore(this);
    // Instantiate the current List of geofences.
    mGeofenceList = new ArrayList<Geofence>();
    // Start with the request flag set to false.
    mInProgress = false;

    createGeofences();
    addGeofences();

    finish();
}
 
Example #12
Source File: ReceiveTransitionsIntentService.java    From Leanplum-Android-SDK with Apache License 2.0 6 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
  try {
    GeofencingEvent event = GeofencingEvent.fromIntent(intent);
    if (event.hasError()) {
      int errorCode = event.getErrorCode();
      Log.d("Location Client Error with code: " + errorCode);
    } else {
      int transitionType = event.getGeofenceTransition();
      List<Geofence> triggeredGeofences = event.getTriggeringGeofences();
      if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER ||
          transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
        LocationManagerImplementation locationManager = (LocationManagerImplementation)
            ActionManager.getLocationManager();
        if (locationManager != null) {
          locationManager.updateStatusForGeofences(triggeredGeofences, transitionType);
        }
      }
    }
  } catch (Throwable t) {
    Util.handleException(t);
  }
}
 
Example #13
Source File: MainActivity.java    From android-Geofencing with Apache License 2.0 6 votes vote down vote up
/**
 * In this sample, the geofences are predetermined and are hard-coded here. A real app might
 * dynamically create geofences based on the user's location.
 */
public void createGeofences() {
    // Create internal "flattened" objects containing the geofence data.
    mAndroidBuildingGeofence = new SimpleGeofence(
            ANDROID_BUILDING_ID,                // geofenceId.
            ANDROID_BUILDING_LATITUDE,
            ANDROID_BUILDING_LONGITUDE,
            ANDROID_BUILDING_RADIUS_METERS,
            GEOFENCE_EXPIRATION_TIME,
            Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT
    );
    mYerbaBuenaGeofence = new SimpleGeofence(
            YERBA_BUENA_ID,                // geofenceId.
            YERBA_BUENA_LATITUDE,
            YERBA_BUENA_LONGITUDE,
            YERBA_BUENA_RADIUS_METERS,
            GEOFENCE_EXPIRATION_TIME,
            Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT
    );

    // Store these flat versions in SharedPreferences and add them to the geofence list.
    mGeofenceStorage.setGeofence(ANDROID_BUILDING_ID, mAndroidBuildingGeofence);
    mGeofenceStorage.setGeofence(YERBA_BUENA_ID, mYerbaBuenaGeofence);
    mGeofenceList.add(mAndroidBuildingGeofence.toGeofence());
    mGeofenceList.add(mYerbaBuenaGeofence.toGeofence());
}
 
Example #14
Source File: Area.java    From mobile-messaging-sdk-android with Apache License 2.0 6 votes vote down vote up
public Geofence toGeofence(Date expiryDate) {
    long expirationDurationMillis = 0L;
    if (expiryDate != null) {
        expirationDurationMillis = expiryDate.getTime() - Time.now();
    }
    if (expirationDurationMillis <= 0) {
        expirationDurationMillis = Geofence.NEVER_EXPIRE;
    }

    return new Geofence.Builder()
            .setCircularRegion(getLatitude(), getLongitude(), getRadius())
            .setRequestId(getId())
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
            .setExpirationDuration(expirationDurationMillis)
            .build();
}
 
Example #15
Source File: MainActivity.java    From effective_android_sample with Apache License 2.0 6 votes vote down vote up
private void addFence(double latitude, double longitude, float radius,
        String requestId, String broadcastUri) {
    if (!servicesConnected()) {
        return;
    }

    Geofence.Builder builder = new Geofence.Builder();
    builder.setRequestId(requestId);
    builder.setCircularRegion(latitude, longitude, radius);
    builder.setExpirationDuration(Geofence.NEVER_EXPIRE); // 無期限
    builder.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER);

    // フェンスのListを作成する。
    List<Geofence> fenceList = new ArrayList<Geofence>();
    fenceList.add(builder.build());

    // フェンス内に入った時に、指定のURIを表示するインテントを投げるようにする。
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(broadcastUri));
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mLocationClient.addGeofences(fenceList, pendingIntent, this);
}
 
Example #16
Source File: GeofenceIntentService.java    From PowerSwitch_Android with GNU General Public License v3.0 6 votes vote down vote up
private boolean geofenceStateChanged(@eu.power_switch.google_play_services.geofence.Geofence.State String state, eu.power_switch.google_play_services.geofence.Geofence.EventType eventType) {
    switch (eventType) {
        case ENTER:
            if (!eu.power_switch.google_play_services.geofence.Geofence.STATE_INSIDE.equals(state)) {
                return true;
            } else {
                return false;
            }
        case EXIT:
            if (!eu.power_switch.google_play_services.geofence.Geofence.STATE_OUTSIDE.equals(state)) {
                return true;
            } else {
                return false;
            }
        default:
            return false;
    }
}
 
Example #17
Source File: UtilityService.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Called when a geofence is triggered
 */
private void geofenceTriggered(Intent intent) {
    Log.v(TAG, ACTION_GEOFENCE_TRIGGERED);

    // Check if geofences are enabled
    boolean geofenceEnabled = Utils.getGeofenceEnabled(this);

    // Extract the geofences from the intent
    GeofencingEvent event = GeofencingEvent.fromIntent(intent);
    List<Geofence> geofences = event.getTriggeringGeofences();

    if (geofenceEnabled && geofences != null && geofences.size() > 0) {
        if (event.getGeofenceTransition() == Geofence.GEOFENCE_TRANSITION_ENTER) {
            // Trigger the notification based on the first geofence
            showNotification(geofences.get(0).getRequestId(), Constants.USE_MICRO_APP);
        } else if (event.getGeofenceTransition() == Geofence.GEOFENCE_TRANSITION_EXIT) {
            // Clear notifications
            clearNotificationInternal();
            clearRemoteNotifications();
        }
    }
    UtilityReceiver.completeWakefulIntent(intent);
}
 
Example #18
Source File: UtilityService.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Called when a geofence is triggered
 */
private void geofenceTriggered(Intent intent) {
    Log.v(TAG, ACTION_GEOFENCE_TRIGGERED);

    // Check if geofences are enabled
    boolean geofenceEnabled = Utils.getGeofenceEnabled(this);

    // Extract the geofences from the intent
    GeofencingEvent event = GeofencingEvent.fromIntent(intent);
    List<Geofence> geofences = event.getTriggeringGeofences();

    if (geofenceEnabled && geofences != null && geofences.size() > 0) {
        if (event.getGeofenceTransition() == Geofence.GEOFENCE_TRANSITION_ENTER) {
            // Trigger the notification based on the first geofence
            showNotification(geofences.get(0).getRequestId(), Constants.USE_MICRO_APP);
        } else if (event.getGeofenceTransition() == Geofence.GEOFENCE_TRANSITION_EXIT) {
            // Clear notifications
            clearNotificationInternal();
            clearRemoteNotifications();
        }
    }
    UtilityReceiver.completeWakefulIntent(intent);
}
 
Example #19
Source File: UtilityService.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Called when a geofence is triggered
 */
private void geofenceTriggered(Intent intent) {
    Log.v(TAG, ACTION_GEOFENCE_TRIGGERED);

    // Check if geofences are enabled
    boolean geofenceEnabled = Utils.getGeofenceEnabled(this);

    // Extract the geofences from the intent
    GeofencingEvent event = GeofencingEvent.fromIntent(intent);
    List<Geofence> geofences = event.getTriggeringGeofences();

    if (geofenceEnabled && geofences != null && geofences.size() > 0) {
        if (event.getGeofenceTransition() == Geofence.GEOFENCE_TRANSITION_ENTER) {
            // Trigger the notification based on the first geofence
            showNotification(geofences.get(0).getRequestId(), Constants.USE_MICRO_APP);
        } else if (event.getGeofenceTransition() == Geofence.GEOFENCE_TRANSITION_EXIT) {
            // Clear notifications
            clearNotificationInternal();
            clearRemoteNotifications();
        }
    }
    UtilityReceiver.completeWakefulIntent(intent);
}
 
Example #20
Source File: GeofencingTest.java    From mobile-messaging-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCalculateRefreshDateForGeoExpiredIfGeoIsMonitoredNow() throws Exception {
    // Given
    long millis15MinBeforeNow = now - 15 * 60 * 1000;
    long millis15MinAfterNow = now + 15 * 60 * 1000;
    String date15MinBeforeNow = DateTimeUtil.ISO8601DateToString(new Date(millis15MinBeforeNow));
    String date15MinAfterNow = DateTimeUtil.ISO8601DateToString(new Date(millis15MinAfterNow));

    saveGeoMessageToDb(date15MinBeforeNow, date15MinAfterNow);

    // When
    Pair<List<Geofence>, Pair<Date, Date>> geofencesAndNextRefreshDate = geofencingImpl.calculateGeofencesToMonitorDates(geoStore);

    // Then
    assertNotNull(geofencesAndNextRefreshDate);
    assertFalse(geofencesAndNextRefreshDate.first.isEmpty());
    assertNull(geofencesAndNextRefreshDate.second.first);
    assertEquals(millis15MinAfterNow, geofencesAndNextRefreshDate.second.second.getTime(), 3000);
}
 
Example #21
Source File: GeofencingTest.java    From mobile-messaging-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotCalculateRefreshDateForGeoStartIfGeoIsMonitoredNow() throws Exception {
    // Given
    Long millis15MinBeforeNow = now - 15 * 60 * 1000;
    Long millis15MinAfterNow = now + 15 * 60 * 1000;
    String date15MinBeforeNow = DateTimeUtil.ISO8601DateToString(new Date(millis15MinBeforeNow));
    String date15MinAfterNow = DateTimeUtil.ISO8601DateToString(new Date(millis15MinAfterNow));

    saveGeoMessageToDb(date15MinBeforeNow, date15MinAfterNow);

    // When
    Pair<List<Geofence>, Pair<Date, Date>> geofencesAndNextRefreshDate = geofencingImpl.calculateGeofencesToMonitorDates(geoStore);

    // Then
    assertNotNull(geofencesAndNextRefreshDate);
    assertFalse(geofencesAndNextRefreshDate.first.isEmpty());
    assertNull(geofencesAndNextRefreshDate.second.first);
}
 
Example #22
Source File: GeofencingTest.java    From mobile-messaging-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCalculateRefreshDateForGeoExpiredIfGeoExpired() throws Exception {
    // Given
    Long millis30MinBeforeNow = now - 30 * 60 * 1000;
    Long millis15MinBeforeNow = now - 15 * 60 * 1000;
    String date30MinBeforeNow = DateTimeUtil.ISO8601DateToString(new Date(millis30MinBeforeNow));
    String date15MinBeforeNow = DateTimeUtil.ISO8601DateToString(new Date(millis15MinBeforeNow));

    saveGeoMessageToDb(date30MinBeforeNow, date15MinBeforeNow);

    // When
    Pair<List<Geofence>, Pair<Date, Date>> geofencesAndNextRefreshDate = geofencingImpl.calculateGeofencesToMonitorDates(geoStore);

    // Then
    assertNotNull(geofencesAndNextRefreshDate);
    assertTrue(geofencesAndNextRefreshDate.first.isEmpty());
    assertNull(geofencesAndNextRefreshDate.second.first);
    assertEquals(now, geofencesAndNextRefreshDate.second.second.getTime(), 3000);
}
 
Example #23
Source File: GeofencingTest.java    From mobile-messaging-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotCalculateRefreshDateForGeoStartIfGeoExpired() throws Exception {
    // Given
    long millis30MinBeforeNow = now - 30 * 60 * 1000;
    long millis15MinBeforeNow = now - 15 * 60 * 1000;
    String date30MinBeforeNow = DateTimeUtil.ISO8601DateToString(new Date(millis30MinBeforeNow));
    String date15MinBeforeNow = DateTimeUtil.ISO8601DateToString(new Date(millis15MinBeforeNow));

    saveGeoMessageToDb(date30MinBeforeNow, date15MinBeforeNow);

    // When
    Pair<List<Geofence>, Pair<Date, Date>> geofencesAndNextRefreshDate = geofencingImpl.calculateGeofencesToMonitorDates(geoStore);

    // Then
    assertNotNull(geofencesAndNextRefreshDate);
    assertTrue(geofencesAndNextRefreshDate.first.isEmpty());
    assertNull(geofencesAndNextRefreshDate.second.first);
}
 
Example #24
Source File: GeofencingTest.java    From mobile-messaging-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCalculateRefreshDatesForGeoStartAndExpired() throws Exception {
    // Given
    long millis15MinAfterNow = now + 15 * 60 * 1000;
    long millis30MinAfterNow = now + 30 * 60 * 1000;
    String date15MinAfterNow = DateTimeUtil.ISO8601DateToString(new Date(millis15MinAfterNow));
    String date30MinAfterNow = DateTimeUtil.ISO8601DateToString(new Date(millis30MinAfterNow));

    saveGeoMessageToDb(date15MinAfterNow, date30MinAfterNow);

    // When
    Pair<List<Geofence>, Pair<Date, Date>> geofencesAndNextRefreshDate = geofencingImpl.calculateGeofencesToMonitorDates(geoStore);

    // Then
    assertNotNull(geofencesAndNextRefreshDate);
    assertTrue(geofencesAndNextRefreshDate.first.isEmpty());
    assertNotNull(geofencesAndNextRefreshDate.second);

    Date refreshStartDate = geofencesAndNextRefreshDate.second.first;
    Date refreshExpiryDate = geofencesAndNextRefreshDate.second.second;
    assertEquals(millis15MinAfterNow, refreshStartDate.getTime(), 3000);
    assertEquals(millis30MinAfterNow, refreshExpiryDate.getTime(), 3000);
}
 
Example #25
Source File: MainActivity.java    From android-Geofencing with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Rather than displayng this activity, simply display a toast indicating that the geofence
    // service is being created. This should happen in less than a second.
    if (!isGooglePlayServicesAvailable()) {
        Log.e(TAG, "Google Play services unavailable.");
        finish();
        return;
    }

    mApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    mApiClient.connect();

    // Instantiate a new geofence storage area.
    mGeofenceStorage = new SimpleGeofenceStore(this);
    // Instantiate the current List of geofences.
    mGeofenceList = new ArrayList<Geofence>();
    createGeofences();
}
 
Example #26
Source File: GeofenceTransitionsIntentService.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
private String getTransitionString(int transitionType) {
    switch (transitionType) {
        case Geofence.GEOFENCE_TRANSITION_ENTER:
            return "Entered";
        case Geofence.GEOFENCE_TRANSITION_EXIT:
            return "Exited";
        default:
            return "Unknown Transition";
    }
}
 
Example #27
Source File: GeofenceTransitionsIntentService.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    if (geofencingEvent.hasError()) {
        String errorMessage = GeofenceErrorMessages.getErrorString(this,
                geofencingEvent.getErrorCode());
        Log.e(TAG, errorMessage);
        return;
    }

    // Get the transition type.
    int geofenceTransition = geofencingEvent.getGeofenceTransition();

    // Test that the reported transition was of interest.
    if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
            geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

        // Get the geofences that were triggered. A single event can trigger multiple geofences.
        List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

        // Get the transition details as a String.
        String geofenceTransitionDetails = getGeofenceTransitionDetails(
                this,
                geofenceTransition,
                triggeringGeofences
        );

        // Send notification and log the transition details.
        sendNotification(geofenceTransitionDetails);
        Log.i(TAG, geofenceTransitionDetails);
    } else {
        // Log the error.
    }
}
 
Example #28
Source File: GeofenceIntentService.java    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Handles incoming intents.
 *
 * @param intent sent by Location Services. This Intent is provided to Location
 *               Services (inside a PendingIntent) when addGeofences() is called.
 */
@Override
protected void onHandleIntent(Intent intent) {
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    if (geofencingEvent.hasError()) {
        Log.e(this, "GeofencingError");
        return;
    }

    // Get the transition type.
    int geofenceTransition = geofencingEvent.getGeofenceTransition();

    // Test that the reported transition was of interest.
    if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
            geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

        // Get the geofences that were triggered. A single event can trigger
        // multiple geofences.
        List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

        // Get the Ids of each geofence that was triggered.
        ArrayList<String> triggeringGeofencesIdsList = new ArrayList<>();
        for (Geofence geofence : triggeringGeofences) {
            triggeringGeofencesIdsList.add(geofence.getRequestId());
        }
        Log.d(this, getTransitionString(geofenceTransition) + ": " + TextUtils.join(", ", triggeringGeofencesIdsList));

        executeGeofences(triggeringGeofences, geofenceTransition);
    } else {
        // Log the error.
        Log.e(this, "Unknown Geofence transition: " + geofenceTransition);
    }
}
 
Example #29
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
private void startGeofence() {
	Location location = mLocationClient.getLastLocation();

	Geofence.Builder builder = new Geofence.Builder();
	mGeofence = builder.setRequestId( FENCE_ID )
			.setCircularRegion( location.getLatitude(), location.getLongitude(), RADIUS )
			.setTransitionTypes( Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT )
			.setExpirationDuration( Geofence.NEVER_EXPIRE )
			.build();

	ArrayList<Geofence> geofences = new ArrayList<Geofence>();
	geofences.add( mGeofence );
	mLocationClient.addGeofences( geofences, mPendingIntent, this );
}
 
Example #30
Source File: GeofenceManager.java    From android-sdk with MIT License 5 votes vote down vote up
private void onGeofencesAdded(Location location, List<Geofence> geofences, int initialTrigger) {
    registered = true;
    updating = false;
    previous = location;
    storePrevious(previous);
    Logger.log.geofence("Successfully added " + geofences.size() +
            " geofences, initial trigger: " + initialTrigger);
    requestLocationUpdates();
}