private GeofencingRequest createGeofencingRequest() { try { double longitude = Double.parseDouble(longitudeInput.getText().toString()); double latitude = Double.parseDouble(latitudeInput.getText().toString()); float radius = Float.parseFloat(radiusInput.getText().toString()); Geofence geofence = new Geofence.Builder() .setRequestId("GEOFENCE") .setCircularRegion(latitude, longitude, radius) .setExpirationDuration(Geofence.NEVER_EXPIRE) .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) .build(); return new GeofencingRequest.Builder().addGeofence(geofence).build(); } catch (NumberFormatException ex) { toast("Error parsing input."); return null; } }
/** * Updates the local {@link ArrayList} of geofences from the data in the passed list *Uses the place id defined by the API as the geofence object id. * * @param places the placeBuffer result of the getPlaceByid call. */ public void updateGeofencesList(PlaceBuffer places){ mGeofenceList = new ArrayList<>(); if (places==null || places.getCount()==0) return; for (Place place: places){ String placeUid = place.getId(); double latitude = place.getLatLng().latitude; double longitude = place.getLatLng().longitude; //Build a geofence object Geofence geofence = new Geofence.Builder() .setRequestId(placeUid) .setExpirationDuration(GEOFENCE_TIMEOUT) .setCircularRegion(latitude,longitude,GEOFENCE_RADIUS) .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) .build(); mGeofenceList.add(geofence); } }
private GeofencingRequest getGeofencingRequest() { if (this.place == null || this.place.getLocation() == null) { return null; } // called when the transition associated with the Geofence is triggered) List<Geofence> geoFenceList = new ArrayList<Geofence>(); geoFenceList.add(new Geofence.Builder() .setRequestId(GEOFENCE_REQUEST_ID) .setCircularRegion(this.place.getLocation().getLatitude(), this.place.getLocation().getLongitude(), GEOFENCE_RADIUS_IN_METERS ) .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_DWELL | Geofence.GEOFENCE_TRANSITION_ENTER) .setLoiteringDelay(LOITERING_DELAY_MS) .setNotificationResponsiveness(NOTIFICATION_RESPONSIVENESS_MS) .setExpirationDuration(Geofence.NEVER_EXPIRE) .build()); GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_DWELL); builder.addGeofences(geoFenceList); return builder.build(); }
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(); }
@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); } }
private void handleLogTransition(int geofenceTransition) { String transitionStr = ""; switch (geofenceTransition) { case Geofence.GEOFENCE_TRANSITION_ENTER: transitionStr = "GEOFENCE_TRANSITION_ENTER"; break; case Geofence.GEOFENCE_TRANSITION_EXIT: transitionStr = "GEOFENCE_TRANSITION_EXIT"; break; case Geofence.GEOFENCE_TRANSITION_DWELL: transitionStr = "GEOFENCE_TRANSITION_DWELL"; break; } Log.d(TAG, transitionStr + " detected! "); }
private static List<Geofence> getGeofenceList(List<Place> places) { List<Geofence> geofenceList = new ArrayList<>(); for (Place place : places){ geofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(String.valueOf(place.getId())) .setCircularRegion( place.getLatitude(), place.getLongitude(), place.getRadius() ) .setExpirationDuration(NEVER_EXPIRE) .setLoiteringDelay(LOITERING_DWELL_DELAY) .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT | Geofence.GEOFENCE_TRANSITION_DWELL) //.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT | Geofence.GEOFENCE_TRANSITION_DWELL) .build()); } return geofenceList; }
/** * Gets transition details and returns them as a formatted string. * * @param context The app context. * @param geofenceTransition The ID of the geofence transition. * @param triggeringGeofences The geofence(s) triggered. * @return The transition details formatted as String. */ 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; }
public GeofencingController(Context context) { this.context = context; // Empty list for storing geofences. mGeofenceList = new ArrayList<Geofence>(); // Initially set the PendingIntent used in addGeofences() and removeGeofences() to null. mGeofencePendingIntent = null; // Retrieve an instance of the SharedPreferences object. mSharedPreferences = context.getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, MODE_PRIVATE); // Get the value of mGeofencesAdded from SharedPreferences. Set to false as a default. mGeofencesAdded = mSharedPreferences.getBoolean(Constants.GEOFENCES_ADDED_KEY, false); // Kick off the request to build GoogleApiClient. buildGoogleApiClient(); }
@Override protected void onHandleIntent(Intent intent) { GeofencingEvent fenceEvent = GeofencingEvent.fromIntent(intent); if (fenceEvent.hasError()) { String errorMessage = GeofenceStatusCodes.getStatusCodeString(fenceEvent.getErrorCode()); Timber.i(errorMessage); return; } Timber.i("We got a geofence intent"); if (fenceEvent.getGeofenceTransition() != Geofence.GEOFENCE_TRANSITION_DWELL || fenceEvent.getTriggeringGeofences().isEmpty()) { return; } String placeId = fenceEvent.getTriggeringGeofences().get(0).getRequestId(); Realm realm = Realm.getDefaultInstance(); Place place = Place.findFirst(realm, placeId); String title = place != null ? getString(R.string.geofence_notification_place_title, place.getName()) : getString(R.string.geofence_notification_title); String content = getString(R.string.geofence_notification_content); String imageUrl = place != null ? place.getFirstImage(GEOFENCE_LARGE_ICON_SIZE) : null; realm.close(); sendNotification(title, content, placeId, imageUrl); }
/** * Concatenates all the id's to one String * @param context from which a call is being made * @param geofenceTransition type of transition * @param triggeringGeofences list of all triggering transitions * @return list of Strings with the type of a transition and all triggering id's */ public static List<String> getTransitionDetails(Context context, int geofenceTransition, List<Geofence> triggeringGeofences) { String geofenceTransitionString = getTransitionString(context, geofenceTransition); // Get the Ids of each geofence that was triggered. List<String> triggeringGeofencesIdsList = new ArrayList<>(); triggeringGeofencesIdsList.add(geofenceTransitionString); for (Geofence geofence : triggeringGeofences) { triggeringGeofencesIdsList.add(geofence.getRequestId()); } return triggeringGeofencesIdsList; }
@Override public void onReceive(Context context, Intent intent) { GeofencingEvent event = GeofencingEvent.fromIntent(intent); if (event.getGeofenceTransition() == Geofence.GEOFENCE_TRANSITION_ENTER) Log.d("aken-ajalukku", "Entered geofence!"); else Log.d("aken-ajalukku", "Exited geofence!"); if (event.getGeofenceTransition() == Geofence.GEOFENCE_TRANSITION_ENTER) { List<Geofence> geofences = event.getTriggeringGeofences(); ArrayList<PointOfInterest> pois = new ArrayList<>(); for (Geofence gf : geofences) { pois.add(Data.instance.getPoiById(Integer.parseInt(gf.getRequestId()))); } createNotification(context, pois); } }
private void populateGeofencesList() { geofences = new ArrayList<>(); for (PointOfInterest poi : Data.instance.getPois()) { geofences.add( new Geofence.Builder() .setRequestId(String.valueOf(poi.getId())) .setCircularRegion(poi.getLocation().latitude, poi.getLocation().longitude, GEOFENCE_RADIUS_IN_METERS) .setExpirationDuration(GEOFENCE_EXPIRATION_IN_MILLISECONDS) .setNotificationResponsiveness(GEOFENCE_RESPONSIVENESS_IN_MILLISECONDS) .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) .build() ); } }
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(); }
@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); }
@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); }
@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); }
@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); }
@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); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); List<Geofence> geofences = new ArrayList<>(); geofences.add(WgCoordinates.getMainBuildingGeofence()); geofences.add(WgCoordinates.getBranchOfficeGeofence()); geofenceHelper = new GeofenceActivityHelper( this, geofences, GeofenceTransitionsIntentService.class, GeofenceHelper.INITIAL_TRIGGER_ENTER | GeofenceHelper.INITIAL_TRIGGER_EXIT); geofenceHelper.update(); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Empty list for storing geofences. mGeofenceList = new ArrayList<Geofence>(); // Initially set the PendingIntent used in addGeofences() and removeGeofences() to null. mGeofencePendingIntent = null; // Get the geofences used. Geofence data is hard coded in this sample. populateGeofenceList(); // Kick off the request to build GoogleApiClient. buildGoogleApiClient(); }
/** * This sample hard codes geofence data. A real app might dynamically create geofences based on * the user's location. */ public void populateGeofenceList() { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(GeofenceTransitionsIntentService.GEOFENCE_KEY) // Set the circular region of this geofence. .setCircularRegion( AppPreferences.getGeofenceLatitude(), AppPreferences.getGeofenceLongitude(), GEOFENCE_RADIUS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Geofence.NEVER_EXPIRE) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); }
@Override protected void onHandleIntent(Intent intent) { GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent); if (geofencingEvent != null && !geofencingEvent.hasError()) { int transition = geofencingEvent.getGeofenceTransition(); // Broadcast an intent containing the geofencing info Intent geofenceIntent = new Intent(BROADCAST_INTENT_ACTION); geofenceIntent.putExtra(TRANSITION_EXTRA_ID, transition); geofenceIntent.putExtra(LOCATION_EXTRA_ID, geofencingEvent.getTriggeringLocation()); ArrayList<String> geofencingIds = new ArrayList<>(); for (Geofence geofence : geofencingEvent.getTriggeringGeofences()) { geofencingIds.add(geofence.getRequestId()); } geofenceIntent.putStringArrayListExtra(GEOFENCES_EXTRA_ID, geofencingIds); sendBroadcast(geofenceIntent); } }
@Override protected void onHandleIntent(Intent intent) { GeofencingEvent event = GeofencingEvent.fromIntent(intent); if (event != null && !event.hasError()) { int transition = event.getGeofenceTransition(); Geofence fence = event.getTriggeringGeofences().get(0); Bundle extras = intent.getExtras(); String id = fence.getRequestId(); Matcher m = Pattern.compile("^([^\\t]+)\\t([^\\t]+)$").matcher(id); if(m.find()){ Uri uri = Uri.parse(m.group(1)); String name = m.group(2); switch (transition) { case Geofence.GEOFENCE_TRANSITION_ENTER: Log.i("TAG", uri.toString()+" "+name); sendNotification(uri, name); break; case Geofence.GEOFENCE_TRANSITION_EXIT: break; } } } }
public void add(GMap.Location location, ResultCallback callback){ Log.i(TAG, "add " + location.toString()); String id = location.url.toString()+"\t"+location.name; Geofence fence = new Geofence.Builder() .setRequestId(id) .setCircularRegion( // 500メートル以内 location.latitude, location.longitude, 500) .setExpirationDuration( // 期限を指定できる Geofence.NEVER_EXPIRE) .setTransitionTypes( Geofence.GEOFENCE_TRANSITION_ENTER) .build(); GeofencingRequest request = new GeofencingRequest.Builder() .addGeofence(fence) // Geofenceを1つ登録 .build(); // IntentServiceで受け取る Intent intent = new Intent(context, GeofenceReceiveService.class); PendingIntent pIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); LocationServices.GeofencingApi .addGeofences(client, request, pIntent) .setResultCallback(callback); }
public void onEvent(EnterFence event) { Geofence geofence; if (event.getGeofences() != null && event.getGeofences().size() > 0) { geofence = event.getGeofences().get(0); } else { return; } for (Geofence fence : mGeofenceList) { if (fence.getRequestId().equals(geofence.getRequestId())) { for (final Node node : mNodes) { if (node.getObjectId().equals(fence.getRequestId())){ onPlayNode(node); return; } } } } }
/** * Gets transition details and returns them as a formatted string. * * @param context The app context. * @param geofenceTransition The ID of the geofence transition. * @param triggeringGeofences The geofence(s) triggered. * @return The transition details formatted as String. */ private String getGeofenceTransitionDetails(Context context, int geofenceTransition, List<Geofence> triggeringGeofences) { String geofenceTransitionString = getTransitionString(geofenceTransition); String pt = ""; // Get the Ids of each geofence that was triggered. ArrayList triggeringGeofencesIdsList = new ArrayList(); for (Geofence geofence : triggeringGeofences) { triggeringGeofencesIdsList.add(geofence.getRequestId()); pt = "" + updateDeviceSettings(geofence.getRequestId(), geofenceTransition); } String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList); return "Profile Type " + pt + "... " + geofenceTransitionString + ": " + triggeringGeofencesIdsString; }
/** 0* Maps geofence transition types to their human-readable equivalents. * * @param transitionType A transition type constant defined in Geofence * @return A String indicating the type of transition */ private String getTransitionString(int transitionType) { switch (transitionType) { case Geofence.GEOFENCE_TRANSITION_ENTER: Log.d(TAG, "entered"); return getString(R.string.geofence_transition_entered); case Geofence.GEOFENCE_TRANSITION_EXIT: Log.d(TAG, "exited"); return getString(R.string.geofence_transition_exited); case Geofence.GEOFENCE_TRANSITION_DWELL: Log.d(TAG, "dwelling"); return ("In the area"); default: Log.e(TAG, "unknown transition"); return getString(R.string.unknown_geofence_transition); } }
/** * Create a storable geofence.<br/> * * Note: If you want to create a dwell geofence, you would certainly prefer {@link StorableGeofence#StorableGeofence(String, String, double, double, float, long, int, int, HashMap)} * * @param geofenceId The Geofence's request ID. * @param pendingIntentClassName full class name of the pending intent that should be triggered when the geofence is activated. * This class should inherit from IntentService * Can be get with YOUR_CLASS.class.getName() * If this class is not correct, a DefaultTransitionsIntentService will be called * @param latitude Latitude of the Geofence's center in degrees. * @param longitude Longitude of the Geofence's center in degrees. * @param radius Radius of the geofence circle in meters. * @param expiration Geofence expiration duration, pass {@link Geofence#NEVER_EXPIRE} if you don't want an expiration date. * @param transition Type of Geofence transition. * @param additionalData Additional data you want to pass. It maps a String to an Object. This Object should be either a String, Long, Integer, Double Boolean or Float */ public StorableGeofence(String geofenceId, String pendingIntentClassName, double latitude, double longitude, float radius, long expiration, int transition, HashMap<String, Object> additionalData) { // Set the instance fields from the constructor. this.mRequestId = geofenceId; this.mPendingIntentClassName = pendingIntentClassName; this.mLatitude = latitude; this.mLongitude = longitude; this.mRadius = radius; this.mExpirationDuration = expiration; this.mLoiteringDelay = 0; this.mTransitionType = transition; if (mExpirationDuration != Geofence.NEVER_EXPIRE) { long nowInMs = new Date().getTime(); mExpirationDateInMs = nowInMs + mExpirationDuration; } else { mExpirationDateInMs = 0; } this.mAdditionalData = additionalData; }
/** * Create a storable geofence * @param geofenceId The Geofence's request ID. * @param pendingIntentClassName full class name of the pending intent that should be triggered when the geofence is activated. * This class should inherit from IntentService * Can be get with YOUR_CLASS.class.getName() * If this class is not correct, a DefaultTransitionsIntentService will be called * @param latitude Latitude of the Geofence's center in degrees. * @param longitude Longitude of the Geofence's center in degrees. * @param radius Radius of the geofence circle in meters. * @param expiration Geofence expiration duration, pass {@link Geofence#NEVER_EXPIRE} if you don't want an expiration date. * @param loiteringDelay Sets the delay between GEOFENCE_TRANSITION_ENTER and GEOFENCE_TRANSITION_DWELLING in milliseconds * This value is ignored if the transition types don't include a GEOFENCE_TRANSITION_DWELL filter. * @param transition Type of Geofence transition. * @param additionalData Additional data you want to pass. It maps a String to an Object. This Object should be either a String, Long, Integer, Double Boolean or Float */ public StorableGeofence(String geofenceId, String pendingIntentClassName, double latitude, double longitude, float radius, long expiration, int loiteringDelay, int transition, HashMap<String, Object> additionalData) { // Set the instance fields from the constructor. this.mRequestId = geofenceId; this.mPendingIntentClassName = pendingIntentClassName; this.mLatitude = latitude; this.mLongitude = longitude; this.mRadius = radius; this.mExpirationDuration = expiration; this.mLoiteringDelay = loiteringDelay; this.mTransitionType = transition; if (mExpirationDuration != Geofence.NEVER_EXPIRE) { long nowInMs = new Date().getTime(); mExpirationDateInMs = nowInMs + mExpirationDuration; } else { mExpirationDateInMs = 0; } this.mAdditionalData = additionalData; }
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; } }
@Override protected void onHandleIntent(Intent intent) { Log.d(TAG, "Geofencing event occured"); GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent); if (geofencingEvent.hasError()) { Log.e(TAG, "Location Services error: " + geofencingEvent.getErrorCode()); return; } Log.i(TAG, "Location Services geofencingEvent: " + geofencingEvent); int transitionType = geofencingEvent.getGeofenceTransition(); List<Geofence> triggeredGeofences = geofencingEvent.getTriggeringGeofences(); for (Geofence geofence : triggeredGeofences) { Log.d(TAG, "onHandle:" + geofence.getRequestId()); processGeofence(geofence, transitionType); } }
public void triggerTransition(Geofences.Geofence fence, int transitionType, boolean hasRelevantUrl) { if (!hasRelevantUrl) { // not global url is set, bail out and show classic notification Log.d(Constants.LOG, "Presenting classic notification for " + fence.uuid); if (mPreferences.getBoolean(Preferences.NOTIFICATION_SUCCESS, false)) { mNotificationManager.showNotification( fence.getRelevantId(), new Random().nextInt(), transitionType ); } } else { Log.d(Constants.LOG, "Dispatching Request for " + fence.uuid); mRequestManager.dispatch(fence, getEventType(transitionType)); } }
/** * 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); }
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; }
@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() ); } }