/// <summary>
        /// Starts monitoring region
        /// </summary>
        /// <param name="region"></param>
        public void StartMonitoring(GeofenceCircularRegion region)
        {
            if (AvailableForMonitoring())
            {
                if (!mRegions.ContainsKey(region.Id))
                {
                    mRegions.Add(region.Id, region);
                }
                else
                {
                    mRegions[region.Id] = region;
                }
                GeofenceStore.SharedInstance.Save(region);

                if (Regions.Count > 20 && locationManager.MonitoredRegions.Count == 20)
                {
                    RecalculateRegions();
                }
                else
                {
                    AddRegion(region);
                }

                locationManager.StartMonitoringSignificantLocationChanges();
            }
        }
Beispiel #2
0
 public void MonitorBackgroundLocation()
 {
     locManager = new CLLocationManager();
     locManager.RequestAlwaysAuthorization();
     locManager.StartMonitoringSignificantLocationChanges();
     locManager.LocationsUpdated += LocationsUpdated;
 }
Beispiel #3
0
        public void StartIntenseLocationScanning( )
        {
            if (AuthorizationStatus == CLAuthorizationStatus.AuthorizedAlways)
            {
                Console.WriteLine("LocationManager: STARTING INTENSE SCANNING.");
                IntenseScanningEnabled = true;

                IntenseScanStartTime = DateTime.Now;

                // if allowed, this will start real-time GPS scanning. This is
                // battery intensive, which is why we'll only use it if the user
                // enters a known tracked region.
                if (CLLocationManager.LocationServicesEnabled)
                {
                    CLLocationManager.PausesLocationUpdatesAutomatically = false;
                    CLLocationManager.StartMonitoringSignificantLocationChanges( );
                    CLLocationManager.AllowsBackgroundLocationUpdates = true;
                    CLLocationManager.StartUpdatingLocation( );
                }
            }
            else
            {
                Console.WriteLine("LocationManager: STARTING INTENSE SCANNING NOT AUTHORIZED. PERMISSIONS {0}", AuthorizationStatus);
            }
        }
Beispiel #4
0
        public void InitializeLocationManager()
        {
            _locationManager = new CLLocationManager();

            if (CLLocationManager.LocationServicesEnabled)
            {
                _locationManager.StartMonitoringSignificantLocationChanges();
            }
            else
            {
                Console.WriteLine("Location services not enabled, please enable this in your Settings");
            }

            _locationManager.LocationsUpdated += (o, e) =>
            {
                var currentLocation = e.Locations.LastOrDefault();
                if (currentLocation != null)
                {
                    App.UserLatitude  = currentLocation.Coordinate.Latitude;
                    App.UserLongitude = currentLocation.Coordinate.Longitude;
                }
                else
                {
                    App.UserLatitude  = 0;
                    App.UserLongitude = 0;
                }
            };
        }
Beispiel #5
0
        static async Task DoStartTracking(LocationTrackingSettings settings)
        {
            CurrentTrackingSettings = settings;

            Manager = await CreateManager();

            if (Device.OS.IsAtLeastiOS(9))
            {
                Manager.AllowsBackgroundLocationUpdates = settings.AllowBackgroundUpdates;
            }

            if (Device.OS.IsAtLeastiOS(6))
            {
                Manager.PausesLocationUpdatesAutomatically = settings.AutoPauseWhenSteady;

                switch (settings.Purpose)
                {
                case LocationTrackingPurpose.AutomotiveNavigation:
                    Manager.ActivityType = CLActivityType.AutomotiveNavigation;
                    break;

                case LocationTrackingPurpose.OtherNavigation:
                    Manager.ActivityType = CLActivityType.OtherNavigation;
                    break;

                case LocationTrackingPurpose.Fitness:
                    Manager.ActivityType = CLActivityType.Fitness;
                    break;

                default:
                    Manager.ActivityType = CLActivityType.Other;
                    break;
                }
            }

            if (CanDeferLocationUpdate && settings.DeferLocationUpdates)
            {
                settings.MovementThreshold = (float)CLLocationDistance.FilterNone;
            }

            IsTracking = true;
            Manager.DesiredAccuracy = CLLocation.AccuracyBest;
            Manager.DistanceFilter  = settings.MovementThreshold;

            if (settings.IgnoreSmallChanges)
            {
                Manager.StartMonitoringSignificantLocationChanges();
            }
            else
            {
                Manager.StartUpdatingLocation();
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            _locationManager = new CLLocationManager();
            _locationManager.Delegate = new MyLocationDelegate();

            // Enable location mode, request if not authorized
            if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways) {
                _locationManager.StartMonitoringSignificantLocationChanges ();
            } else {
                _locationManager.RequestAlwaysAuthorization ();
            }
        }
Beispiel #7
0
        public void PromtUserToEnableLocationService(Action callcack)
        {
            if (CLLocationManager.Status == CLAuthorizationStatus.Authorized)
            {
                return;
            }

            _onSuccessEnableLocationCallback       = callcack;
            _locationManager.AuthorizationChanged += HandleAuthorizationChanged;

            if (CLLocationManager.Status == CLAuthorizationStatus.NotDetermined)
            {
                _locationManager.StartMonitoringSignificantLocationChanges();
                _locationManager.StopMonitoringSignificantLocationChanges();
            }
            else if (
                CLLocationManager.Status == CLAuthorizationStatus.Restricted ||
                CLLocationManager.Status == CLAuthorizationStatus.Denied
                )
            {
                UIAlertView alert = new UIAlertView("Need to enable location service", "To use this feature you must enable location service in settings", null, "Ok");
                alert.Show();
            }
        }
Beispiel #8
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			// Perform any additional setup after loading the view, typically from a nib.

			var LocationManager = new CLLocationManager();
			LocationManager.RequestWhenInUseAuthorization ();
			LocationManager.RequestAlwaysAuthorization ();

			CLCircularRegion region = new CLCircularRegion (new CLLocationCoordinate2D (+46.833120, +15.34901), 1000.0, "FF Gussendorf");

			if (CLLocationManager.LocationServicesEnabled) {

				LocationManager.DidStartMonitoringForRegion += (o, e) => {
					Console.WriteLine ("Now monitoring region {0}", e.Region.ToString ());
				};

				LocationManager.RegionEntered += (o, e) => {
					Console.WriteLine ("Just entered " + e.Region.ToString ());
				};

				LocationManager.RegionLeft += (o, e) => {
					Console.WriteLine ("Just left " + e.Region.ToString ());
				};

				LocationManager.Failed += (o, e) => {
					Console.WriteLine (e.Error);
				};

				LocationManager.UpdatedLocation += (o, e) => {
					Console.WriteLine ("Lat " + e.NewLocation.Coordinate.Latitude + ", Long " + e.NewLocation.Coordinate.Longitude);
				};

				LocationManager.LocationsUpdated += (o, e) => Console.WriteLine ("Location change received");

				LocationManager.StartMonitoring (region);
				LocationManager.StartMonitoringSignificantLocationChanges ();

				//LocationManager.StopMonitoringSignificantLocationChanges ();



			} else {
				Console.WriteLine ("This app requires region monitoring, which is unavailable on this device");
			}
		}
        public override void ViewDidLoad()
        {
            this.locationManager = new CLLocationManager();
            locationManager.StartMonitoringSignificantLocationChanges();
            tapitAd.WillLoadAd += HandleWillLoadAd;

            tapitAd.DidFinish += HandleDidFinish;

            tapitAd.DidLoadAd += HandleDidLoadAd;
            tapitAd.FailedToReceiveAd += HandleFailedToReceiveAd;
            NSDictionary parameters = NSDictionary.FromObjectAndKey( new NSString("test"),new NSString("mode"));
            request = TapItRequest.FromZone(AppDelegate.ZoneId,parameters);
            if(locationManager.Location != null)
                request.UpdateLocation(locationManager.Location);
            tapitAd.StartServingAds(request);

            button.TouchDown += HandleTouchDown;
        }
Beispiel #10
0
        public override void ViewDidLoad()
        {
            this.locationManager = new CLLocationManager();
            locationManager.StartMonitoringSignificantLocationChanges();
            tapitAd.WillLoadAd += HandleWillLoadAd;

            tapitAd.DidFinish += HandleDidFinish;

            tapitAd.DidLoadAd         += HandleDidLoadAd;
            tapitAd.FailedToReceiveAd += HandleFailedToReceiveAd;
            NSDictionary parameters = NSDictionary.FromObjectAndKey(new NSString("test"), new NSString("mode"));

            request = TapItRequest.FromZone(AppDelegate.ZoneId, parameters);
            if (locationManager.Location != null)
            {
                request.UpdateLocation(locationManager.Location);
            }
            tapitAd.StartServingAds(request);

            button.TouchDown += HandleTouchDown;
        }
Beispiel #11
0
        //SERVICE FUNCTIONS

        public void Start(int interval)
        {
            locationManager = new CLLocationManager();
            locationManager.PausesLocationUpdatesAutomatically = false;

            locationManager.RequestAlwaysAuthorization();
            locationManager.AllowsBackgroundLocationUpdates = true;

            if (CLLocationManager.LocationServicesEnabled)
            {
                //set the desired accuracy, in meters
                locationManager.DesiredAccuracy = CLLocation.AccurracyBestForNavigation;
                locationManager.DistanceFilter  = CLLocationDistance.FilterNone;


                var locationDelegate = new MyLocationDelegate();
                locationManager.Delegate = locationDelegate;
                locationManager.AllowDeferredLocationUpdatesUntil(CLLocationDistance.MaxDistance, interval);

                locationManager.StartUpdatingLocation();
                locationManager.StartMonitoringSignificantLocationChanges();
                //locationDelegate.StartTimer(interval);
            }
        }
 public override void AuthorizationChanged(CLLocationManager manager, CLAuthorizationStatus status)
 {
     if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways) {
         manager.StartMonitoringSignificantLocationChanges ();
     }
 }
Beispiel #13
0
    private void OnGUI()
    {
        KitchenSink.OnGUIBack();

        GUILayout.BeginArea(new Rect(50, 50, Screen.width - 100, Screen.height / 2 - 50));

        //this is the original way of how objective C use call back functions: Delegates using separate files.
        //in this case the file is PeoplePickerNavigationControllerDelegate.cs
        //we have have it easier to use delegates instead of creating new files for each delegate.
        //see examples above.  Ex: PersonalXT.CalendarAccess += delegate( ....
        if (GUILayout.Button("pick/select from contacts", GUILayout.ExpandHeight(true)))
        {
            ABPeoplePickerNavigationController picker = new ABPeoplePickerNavigationController();
            if (pickerDelegate == null)
            {
                pickerDelegate = new PeoplePickerNavigationControllerDelegate();
            }
            picker.peoplePickerDelegate = pickerDelegate;
            UIApplication.deviceRootViewController.PresentViewController(picker, true, null);
        }

        if (GUILayout.Button("get all contacts", GUILayout.ExpandHeight(true)))
        {
            Log("Address book authorization status: " + ABAddressBook.GetAuthorizationStatus());

            var addressBook = ABAddressBook.Create(null, null);
            addressBook.RequestAccess(delegate(bool granted, NSError error) {
                Log("Granted: " + granted);

                //convienent function to get the names of the contacts
                string[] contactList = PersonalXT.GetAllContactNames();
                for (int i = 0; i < contactList.Length; i++)
                {
                    Log("Contact " + i + ": " + contactList[i]);
                }
            });
        }

        if (GUILayout.Button("add new contacts", GUILayout.ExpandHeight(true)))
        {
            addNewContact();
        }

        if (GUILayout.Button("init Calendar and show events within 30 days", GUILayout.ExpandHeight(true)))
        {
            checkEventStoreAccessForCalendar();
        }

        if (GUILayout.Button("add an event for tomorrow", GUILayout.ExpandHeight(true)))
        {
            addEventForTomorrow();
        }

        if (GUILayout.Button("add alarm to events", GUILayout.ExpandHeight(true)))
        {
            createAlarmForEvents();
        }

        if (GUILayout.Button("add reminder with geolocation of current location", GUILayout.ExpandHeight(true)))
        {
            PersonalXT.RequestReminderAccess();
        }

        if (GUILayout.Button("reverse geocode happiest place on earth", GUILayout.ExpandHeight(true)))
        {
            CLLocation location = new CLLocation(33.809, -117.919);
            CLGeocoder geocoder = new CLGeocoder();
            geocoder.ReverseGeocodeLocation(location, delegate(object[] placemarks, NSError error) {
                if (error != null)
                {
                    Debug.Log(error.LocalizedDescription());
                }
                else
                {
                    foreach (var p in placemarks)
                    {
                        var placemark = p as CLPlacemark;

                        Debug.Log("placemark: " + placemark.name + "\n"
                                  + ABAddressFormatting.ABCreateString(placemark.addressDictionary, true));
                    }
                }
            });
        }

        if (GUILayout.Button("Significant location change", GUILayout.ExpandHeight(true)))
        {
            if (!CLLocationManager.LocationServicesEnabled() || !CLLocationManager.SignificantLocationChangeMonitoringAvailable())
            {
                Debug.Log("Significant change monitoring not available.");
            }
            else
            {
//				CLLocationManager manager = new CLLocationManager();

                manager.StartMonitoringSignificantLocationChanges();
            }
        }


        //commented out remove all events and reminders so users don't accidentally remove important events

        /*
         * if (GUILayout.Button("remove all Events", GUILayout.ExpandHeight(true))) {
         *      PersonalXT.RemoveAllEvents();
         *      Log ("Removed events");
         * }
         *
         * if (GUILayout.Button("remove all Reminders", GUILayout.ExpandHeight(true))) {
         *      PersonalXT.GetAllReminders(); //you can get all the reminders and handle them in line 59 above
         *      //PersonalXT.RemoveAllReminders(); //or you can simply call removeAllReminders
         * }*/

        GUILayout.EndArea();
        OnGUILog();
    }
Beispiel #14
0
        public async Task <bool> StartListeningAsync(TimeSpan minimumTime, double minimumDistance, bool includeHeading = false, ListenerSettings listenerSettings = null)
        {
            if (minimumDistance < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(minimumDistance));
            }

            if (isListening)
            {
                throw new InvalidOperationException("Already listening");
            }

            // if no settings were passed in, instantiate the default settings. need to check this and create default settings since
            // previous calls to StartListeningAsync might have already configured the location manager in a non-default way that the
            // caller of this method might not be expecting. the caller should expect the defaults if they pass no settings.
            if (listenerSettings == null)
            {
                listenerSettings = new ListenerSettings();
            }

#if __IOS__
            var permission = Permission.Location;
            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                if (listenerSettings.AllowBackgroundUpdates)
                {
                    permission = Permission.LocationAlways;
                }
                else
                {
                    permission = Permission.LocationWhenInUse;
                }
            }

            var hasPermission = await CheckPermissions(permission);


            if (!hasPermission)
            {
                throw new GeolocationException(GeolocationError.Unauthorized);
            }
#endif

            // keep reference to settings so that we can stop the listener appropriately later
            this.listenerSettings = listenerSettings;

            var desiredAccuracy = DesiredAccuracy;

            // set background flag
#if __IOS__
            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                manager.AllowsBackgroundLocationUpdates = listenerSettings.AllowBackgroundUpdates;
            }

            // configure location update pausing
            if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
            {
                manager.PausesLocationUpdatesAutomatically = listenerSettings.PauseLocationUpdatesAutomatically;

                switch (listenerSettings.ActivityType)
                {
                case ActivityType.AutomotiveNavigation:
                    manager.ActivityType = CLActivityType.AutomotiveNavigation;
                    break;

                case ActivityType.Fitness:
                    manager.ActivityType = CLActivityType.Fitness;
                    break;

                case ActivityType.OtherNavigation:
                    manager.ActivityType = CLActivityType.OtherNavigation;
                    break;

                default:
                    manager.ActivityType = CLActivityType.Other;
                    break;
                }
            }
#endif

            // to use deferral, CLLocationManager.DistanceFilter must be set to CLLocationDistance.None, and CLLocationManager.DesiredAccuracy must be
            // either CLLocation.AccuracyBest or CLLocation.AccuracyBestForNavigation. deferral only available on iOS 6.0 and above.
            if (CanDeferLocationUpdate && listenerSettings.DeferLocationUpdates)
            {
                minimumDistance = CLLocationDistance.FilterNone;
                desiredAccuracy = CLLocation.AccuracyBest;
            }

            isListening             = true;
            manager.DesiredAccuracy = desiredAccuracy;
            manager.DistanceFilter  = minimumDistance;

#if __IOS__ || __MACOS__
            if (listenerSettings.ListenForSignificantChanges)
            {
                manager.StartMonitoringSignificantLocationChanges();
            }
            else
            {
                manager.StartUpdatingLocation();
            }
#elif __TVOS__
            //not supported
#endif

#if __IOS__
            if (includeHeading && CLLocationManager.HeadingAvailable)
            {
                manager.StartUpdatingHeading();
            }
#endif

            return(true);
        }
 public void OnSleep()
 {
     _locationManager.StartMonitoringSignificantLocationChanges();
 }
Beispiel #16
0
 public void StartListeningForSignificantLocationChanges()
 {
     _manager.StartMonitoringSignificantLocationChanges();
 }
Beispiel #17
0
        private void MonitorLocation(UIApplicationState appState)
        {
            if (CLLocationManager.LocationServicesEnabled)
            {
                LastSentLocationTime  = new DateTime(0);
                FirstSentLocationTime = new DateTime(0);
                Console.WriteLine("MONITOR LOCATION");

                GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent("app_action", "location", "monitor location", null).Build());

                LocationManager = new CLLocationManager();
                LocationManager.DesiredAccuracy = 10;
                LocationManager.PausesLocationUpdatesAutomatically = false;

                LocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
                    CLLocation currentLocation  = e.Locations[e.Locations.Length - 1];
                    DateTime   locationDateTime = DateTime.SpecifyKind(currentLocation.Timestamp, DateTimeKind.Utc);

                    double timeremaining = UIApplication.SharedApplication.BackgroundTimeRemaining;

                    Console.WriteLine("LOCATION UPDATE - Time Remaining: " + timeremaining.ToString());

                    if (LastSentLocationTime.Ticks == 0)
                    {
                        Console.WriteLine("FIRST LOCATION SENT");
                        sendLocation(currentLocation);
                        FirstSentLocationTime = locationDateTime;
                        LastSentLocationTime  = locationDateTime;
                    }
                    else
                    {
                        var diffInSeconds = (locationDateTime - LastSentLocationTime).TotalSeconds;
                        if (diffInSeconds >= 10.0)
                        {
                            Console.WriteLine("LOCATION SENT");
                            GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent("app_action", "location", "location sent", null).Build());
                            sendLocation(currentLocation);
                            LastSentLocationTime = locationDateTime;
                        }

                        var diffInSecondsFromFirst = (locationDateTime - FirstSentLocationTime).TotalSeconds;
                        if (diffInSecondsFromFirst >= 120)
                        {
                            Console.WriteLine("STOP MONITOR LOCATION");
                            GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent("app_action", "location", "stop monitor location", null).Build());
                            if (LocationManager != null)
                            {
                                LocationManager.StopUpdatingLocation();
                                LocationManager.StopMonitoringSignificantLocationChanges();
                            }

                            LocationManager = null;
                        }
                    }
                };


                if (appState == UIApplicationState.Active)
                {
                    LocationManager.StartUpdatingLocation();
                }
                else
                {
                    LocationManager.StartMonitoringSignificantLocationChanges();
                }
            }
            else
            {
                Console.WriteLine("Location services not enabled");
            }
        }
Beispiel #18
0
 public void RestoreMonitoring()
 {
     _manager.StartMonitoringSignificantLocationChanges();
 }
Beispiel #19
0
        protected override void InternalStart()
        {
            lock (_locker)
            {
                base.InternalStart();

#if __IOS__
                string userNotificationMessage = DisplayName + " data requested.";
#elif __ANDROID__
                string userNotificationMessage = null;
#elif LOCAL_TESTS
                string userNotificationMessage = null;
#else
#warning "Unrecognized platform"
                string userNotificationMessage = null;
#endif

                _pollCallback = new ScheduledCallback((callbackId, cancellationToken, letDeviceSleepCallback) =>
                {
                    return(Task.Run(async() =>
                    {
                        if (Running)
                        {
                            _isPolling = true;

                            IEnumerable <Datum> data = null;
                            try
                            {
                                SensusServiceHelper.Get().Logger.Log("Polling.", LoggingLevel.Normal, GetType());
                                data = Poll(cancellationToken);

                                lock (_pollTimes)
                                {
                                    _pollTimes.Add(DateTime.Now);
                                    _pollTimes.RemoveAll(pollTime => pollTime < Protocol.ParticipationHorizon);
                                }
                            }
                            catch (Exception ex)
                            {
                                SensusServiceHelper.Get().Logger.Log("Failed to poll:  " + ex.Message, LoggingLevel.Normal, GetType());
                            }

                            if (data != null)
                            {
                                foreach (Datum datum in data)
                                {
                                    if (cancellationToken.IsCancellationRequested)
                                    {
                                        break;
                                    }

                                    try
                                    {
                                        await StoreDatumAsync(datum, cancellationToken);
                                    }
                                    catch (Exception ex)
                                    {
                                        SensusServiceHelper.Get().Logger.Log("Failed to store datum:  " + ex.Message, LoggingLevel.Normal, GetType());
                                    }
                                }
                            }

                            _isPolling = false;
                        }
                    }));
                }, TimeSpan.Zero, TimeSpan.FromMilliseconds(_pollingSleepDurationMS), POLL_CALLBACK_LAG, GetType().FullName, Protocol.Id, Protocol, TimeSpan.FromMinutes(_pollingTimeoutMinutes), userNotificationMessage);

#if __IOS__
                if (_significantChangePoll)
                {
                    _locationManager.RequestAlwaysAuthorization();
                    _locationManager.DistanceFilter = 5.0;
                    _locationManager.PausesLocationUpdatesAutomatically = false;
                    _locationManager.AllowsBackgroundLocationUpdates    = true;

                    if (CLLocationManager.LocationServicesEnabled)
                    {
                        _locationManager.StartMonitoringSignificantLocationChanges();
                    }
                    else
                    {
                        SensusServiceHelper.Get().Logger.Log("Location services not enabled.", LoggingLevel.Normal, GetType());
                    }
                }

                // schedule the callback if we're not doing significant-change polling, or if we are but the latter doesn't override the former.
                if (!_significantChangePoll || !_significantChangePollOverridesScheduledPolls)
                {
                    SensusContext.Current.CallbackScheduler.ScheduleCallback(_pollCallback);
                }
#elif __ANDROID__
                SensusContext.Current.CallbackScheduler.ScheduleCallback(_pollCallback);
#endif
            }
        }
      /// <summary>
      /// Geofence plugin iOS implementation
      /// </summary>
      public GeofenceImplementation()
      {

          mGeofenceResults = new Dictionary<string, GeofenceResult>();

          locationManager = new CLLocationManager();
          locationManager.DidStartMonitoringForRegion += DidStartMonitoringForRegion;
          locationManager.RegionEntered += RegionEntered;
          locationManager.RegionLeft +=RegionLeft;
          locationManager.Failed += OnFailure;
          locationManager.DidDetermineState += DidDetermineState;
          locationManager.LocationsUpdated += LocationsUpdated;
          string priorityType = "Balanced Power";
          switch(CrossGeofence.GeofencePriority)
          {
              case GeofencePriority.HighAccuracy:
                  priorityType = "High Accuracy";
                  locationManager.DesiredAccuracy = CLLocation.AccuracyBest;
                  break;
              case GeofencePriority.AcceptableAccuracy:
                  priorityType = "Acceptable Accuracy";
                  locationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;
                  break;
              case GeofencePriority.MediumAccuracy:
                  priorityType = "Medium Accuracy";
                  locationManager.DesiredAccuracy = CLLocation.AccuracyHundredMeters;
                  break;
              case GeofencePriority.LowAccuracy:
                  priorityType = "Low Accuracy";
                  locationManager.DesiredAccuracy = CLLocation.AccuracyKilometer;
                  break;
              case GeofencePriority.LowestAccuracy:
                  priorityType = "Lowest Accuracy";
                  locationManager.DesiredAccuracy = CLLocation.AccuracyThreeKilometers;
                  break;
              default:
                  locationManager.DesiredAccuracy = CLLocation.AccurracyBestForNavigation;
                  break;
          }
          System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}: {2}", CrossGeofence.Id, "Location priority set to", priorityType));
    
          if(CrossGeofence.SmallestDisplacement>0)
          {
              locationManager.DistanceFilter = CrossGeofence.SmallestDisplacement;
              System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}: {2} meters", CrossGeofence.Id, "Location smallest displacement set to", CrossGeofence.SmallestDisplacement));
          }

         

          if (locationManager.MonitoredRegions.Count > 0 && IsMonitoring)
          {

              NSSet monitoredRegions = locationManager.MonitoredRegions;
             

              foreach (CLCircularRegion region in monitoredRegions)
              {
                  //If not on regions remove on startup since that region was set not persistent
                  if (!Regions.ContainsKey(region.Identifier))
                  {
                      locationManager.StopMonitoring(region);
                  }
                  else
                  {
                      locationManager.RequestState(region);
                  }
                 
              }

              locationManager.StartMonitoringSignificantLocationChanges();

              string message = string.Format("{0} - {1} {2} region(s)", CrossGeofence.Id, "Actually monitoring", locationManager.MonitoredRegions.Count);
              System.Diagnostics.Debug.WriteLine(message);
              
          }

          SetLastKnownLocation(locationManager.Location);
          
      }
        /// <summary>
        /// Geofence plugin iOS implementation
        /// </summary>
        public GeofenceImplementation()
        {
            mGeofenceResults = new Dictionary <string, GeofenceResult>();

            using (var pool = new NSAutoreleasePool())
            {
                pool.InvokeOnMainThread(() => {
                    locationManager = new CLLocationManager();
                    locationManager.DidStartMonitoringForRegion += DidStartMonitoringForRegion;
                    locationManager.RegionEntered     += RegionEntered;
                    locationManager.RegionLeft        += RegionLeft;
                    locationManager.Failed            += OnFailure;
                    locationManager.DidDetermineState += DidDetermineState;
                    locationManager.LocationsUpdated  += LocationsUpdated;
                });
            }
            string priorityType = "Balanced Power";

            switch (CrossGeofence.GeofencePriority)
            {
            case GeofencePriority.HighAccuracy:
                priorityType = "High Accuracy";
                locationManager.DesiredAccuracy = CLLocation.AccuracyBest;
                break;

            case GeofencePriority.AcceptableAccuracy:
                priorityType = "Acceptable Accuracy";
                locationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;
                break;

            case GeofencePriority.MediumAccuracy:
                priorityType = "Medium Accuracy";
                locationManager.DesiredAccuracy = CLLocation.AccuracyHundredMeters;
                break;

            case GeofencePriority.LowAccuracy:
                priorityType = "Low Accuracy";
                locationManager.DesiredAccuracy = CLLocation.AccuracyKilometer;
                break;

            case GeofencePriority.LowestAccuracy:
                priorityType = "Lowest Accuracy";
                locationManager.DesiredAccuracy = CLLocation.AccuracyThreeKilometers;
                break;

            default:
                locationManager.DesiredAccuracy = CLLocation.AccurracyBestForNavigation;
                break;
            }
            System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}: {2}", CrossGeofence.Id, "Location priority set to", priorityType));

            if (CrossGeofence.SmallestDisplacement > 0)
            {
                locationManager.DistanceFilter = CrossGeofence.SmallestDisplacement;
                System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}: {2} meters", CrossGeofence.Id, "Location smallest displacement set to", CrossGeofence.SmallestDisplacement));
            }



            if (locationManager.MonitoredRegions.Count > 0 && IsMonitoring)
            {
                NSSet monitoredRegions = locationManager.MonitoredRegions;


                foreach (CLCircularRegion region in monitoredRegions)
                {
                    //If not on regions remove on startup since that region was set not persistent
                    if (!Regions.ContainsKey(region.Identifier))
                    {
                        locationManager.StopMonitoring(region);
                    }
                    else
                    {
                        locationManager.RequestState(region);
                    }
                }

                locationManager.StartMonitoringSignificantLocationChanges();

                string message = string.Format("{0} - {1} {2} region(s)", CrossGeofence.Id, "Actually monitoring", locationManager.MonitoredRegions.Count);
                System.Diagnostics.Debug.WriteLine(message);
            }

            SetLastKnownLocation(locationManager.Location);
        }
Beispiel #22
0
        /// <summary>
        /// Start listening for changes
        /// </summary>
        /// <param name="minimumTime">Time</param>
        /// <param name="minimumDistance">Distance</param>
        /// <param name="includeHeading">Include heading or not</param>
        /// <param name="listenerSettings">Optional settings (iOS only)</param>
        public Task <bool> StartListeningAsync(TimeSpan minTime, double minDistance, bool includeHeading = false, ListenerSettings settings = null)
        {
            if (minDistance < 0)
            {
                throw new ArgumentOutOfRangeException("minDistance");
            }
            if (isListening)
            {
                throw new InvalidOperationException("Already listening");
            }

            // if no settings were passed in, instantiate the default settings. need to check this and create default settings since
            // previous calls to StartListeningAsync might have already configured the location manager in a non-default way that the
            // caller of this method might not be expecting. the caller should expect the defaults if they pass no settings.
            if (settings == null)
            {
                settings = new ListenerSettings();
            }

            // keep reference to settings so that we can stop the listener appropriately later
            listenerSettings = settings;

            var desiredAccuracy = DesiredAccuracy;

            #region apply settings to location manager
            // set background flag
            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                manager.AllowsBackgroundLocationUpdates = settings.AllowBackgroundUpdates;
            }

            // configure location update pausing
            if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
            {
                manager.PausesLocationUpdatesAutomatically = settings.PauseLocationUpdatesAutomatically;

                if (settings.ActivityType == ActivityType.AutomotiveNavigation)
                {
                    manager.ActivityType = CLActivityType.AutomotiveNavigation;
                }
                else if (settings.ActivityType == ActivityType.Fitness)
                {
                    manager.ActivityType = CLActivityType.Fitness;
                }
                else if (settings.ActivityType == ActivityType.Other)
                {
                    manager.ActivityType = CLActivityType.Other;
                }
                else if (settings.ActivityType == ActivityType.OtherNavigation)
                {
                    manager.ActivityType = CLActivityType.OtherNavigation;
                }
            }

            // to use deferral, CLLocationManager.DistanceFilter must be set to CLLocationDistance.None, and CLLocationManager.DesiredAccuracy must be
            // either CLLocation.AccuracyBest or CLLocation.AccuracyBestForNavigation. deferral only available on iOS 6.0 and above.
            if (CanDeferLocationUpdate && settings.DeferLocationUpdates)
            {
                minDistance     = CLLocationDistance.FilterNone;
                desiredAccuracy = CLLocation.AccuracyBest;
            }
            #endregion

            isListening             = true;
            manager.DesiredAccuracy = desiredAccuracy;
            manager.DistanceFilter  = minDistance;

            if (settings.ListenForSignificantChanges)
            {
                manager.StartMonitoringSignificantLocationChanges();
            }
            else
            {
                manager.StartUpdatingLocation();
            }

            if (includeHeading && CLLocationManager.HeadingAvailable)
            {
                manager.StartUpdatingHeading();
            }

            return(Task.FromResult(true));
        }