public static void ShowProgressDialog(string title, string message, Action action, Action finalize) { UIAlertView dialog = new UIAlertView(title, message, null, null); dialog.Show(); _indicatorViewLeftCorner.Hidden = false; ThreadPool.QueueUserWorkItem(delegate { // Run the given Async task action(); // Run the completion handler on the UI thread and remove the spinner using (var pool = new NSAutoreleasePool()) { try { pool.InvokeOnMainThread(() => { dialog.DismissWithClickedButtonIndex(0, true); _indicatorViewLeftCorner.Hidden = true; finalize(); }); } catch (Exception ex){ Insights.Report(ex); } } }); }
void CreateNotification(string title, string message) { // Do nothing if we have no notification permission at this time, or we will get a buildup of stale notifications if (UIApplication.SharedApplication.CurrentUserNotificationSettings.Types == UIUserNotificationType.None) { return; } // Create notifications on main thread, this method can be invoked from a background thread using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread(() => { var notification = new UILocalNotification(); notification.AlertAction = title; notification.AlertBody = message; notification.HasAction = true; notification.SoundName = UILocalNotification.DefaultSoundName; #if __UNIFIED__ UIApplication.SharedApplication.PresentLocalNotificationNow(notification); #else UIApplication.SharedApplication.PresentLocationNotificationNow(notification); #endif }); } }
public static void ShowProgressDialog(string title, string message, Action action, Action finalize) { UIAlertView dialog = new UIAlertView(title, message, null, null); dialog.Show(); _indicatorViewLeftCorner.Hidden = false; ThreadPool.QueueUserWorkItem(delegate { // Run the given Async task action(); // Run the completion handler on the UI thread and remove the spinner using (var pool = new NSAutoreleasePool()) { try { pool.InvokeOnMainThread(() => { dialog.DismissWithClickedButtonIndex(0, true); _indicatorViewLeftCorner.Hidden = true; finalize(); }); } catch (Exception ex) { Insights.Report(ex); } } }); }
private void ExecuteCommandThread() { using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread(delegate { ExecuteMethod(() => Animating = false); }); } }
private void HandleGetPicturesCompleted (object sender, Loewenbraeu.Data.Service.GetPicturesCompletedEventArgs args) { bool error = ServiceAgent.HandleAsynchCompletedError (args, "GetEvents"); using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread (delegate { Util.PopNetworkActive (); if (error) return; List<Picture> result = args.Result.ToList (); ShowGalery (result); }); } }
/// <summary> /// Checks if is available for monitoring /// </summary> /// <returns></returns> public bool AvailableForMonitoring() { bool retVal = false; RequestAlwaysAuthorization(); if (!CLLocationManager.LocationServicesEnabled) { string message = string.Format("{0} - {1}", CrossGeofence.Id, "You need to enable Location Services"); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } else if (CLLocationManager.Status == CLAuthorizationStatus.Denied || CLLocationManager.Status == CLAuthorizationStatus.Restricted) { string message = string.Format("{0} - {1}", CrossGeofence.Id, "You need to authorize Location Services"); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } else if (CLLocationManager.IsMonitoringAvailable(typeof(CLRegion))) { if (RequestNotificationPermission) { using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread(() => { var settings = UIUserNotificationSettings.GetSettingsForTypes( UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, new NSSet()); UIApplication.SharedApplication.RegisterUserNotificationSettings(settings); }); } } retVal = true; } else { string message = string.Format("{0} - {1}", CrossGeofence.Id, "Not available for monitoring"); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } return(retVal); }
void RequestAlwaysAuthorization() { if (!RequestLocationPermission) { return; } if (isPromptingLocationPermission) { return; } isPromptingLocationPermission = true; CLAuthorizationStatus status = CLLocationManager.Status; if (status == CLAuthorizationStatus.AuthorizedWhenInUse || status == CLAuthorizationStatus.Denied) { using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread(() => { UIAlertView alertView = new UIAlertView() { Title = (status == CLAuthorizationStatus.Denied) ? "Location services are off" : "Background location is not enabled", Message = "To use background location you must turn on 'Always' in the Location Services Settings" }; alertView.AddButton("OK"); alertView.Clicked += (sender, buttonArgs) => { if (buttonArgs.ButtonIndex == 1) { // Send the user to the Settings for this app NSUrl settingsUrl = new NSUrl(UIApplication.OpenSettingsUrlString); UIApplication.SharedApplication.OpenUrl(settingsUrl); } isPromptingLocationPermission = false; }; alertView.Show(); }); } } else if (status == CLAuthorizationStatus.NotDetermined) { locationManager.RequestAlwaysAuthorization(); } }
public void Invoke(Action action) { using (var pool = new NSAutoreleasePool()) { try { pool.InvokeOnMainThread(delegate { action.Invoke(); }); } catch (Exception) { //TODO : Error msg ? } } }
protected virtual void OnUsageUpdated() { // Usage info comes from an async request, it could be on any thread // So we need to make sure we have a release pool for ObjC code in the thread // We also need to ensure we get back on the UI thread to prevent potential cross-thread issues using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread(() => { UsageInformation usage; lock (_lockObject) usage = _currentUsage; if (UsageUpdated != null) { UsageUpdated(this, new UsageUpdatedEventArgs(usage)); } }); } }
private void HandleIsDeclinedByRestaurantCompleted (object sender, IsDeclinedByRestaurantCompletedEventArgs args) { bool error = ServiceAgent.HandleAsynchCompletedError (args, "GetEvents"); using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread (delegate { Util.PopNetworkActive (); if (error) return; if (args.Result == true) { _reservation.Status = StatusArt.DeclinedByRestaurant; ReservationRepository.Update (_reservation); ShowConfirmReservationView (_reservation); //StopTimer (); } else { ShowCodeConfirmView (_reservation); } }); } }
public iOSNavigationManager(ITinyMessengerHub messageHub) { _messageHub = messageHub; _messageHub.Subscribe<MobileNavigationManagerCommandMessage>((m) => { using(var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread(() => { switch(m.CommandType) { case MobileNavigationManagerCommandMessageType.ShowPlayerView: var navCtrl = (SessionsNavigationController)m.Sender; CreatePlayerView(navCtrl.TabType); break; case MobileNavigationManagerCommandMessageType.ShowEqualizerPresetsView: CreateEqualizerPresetsView(null); break; case MobileNavigationManagerCommandMessageType.ShowPlaylistView: CreatePlaylistView(null); break; } }); } }); }
public void DownloadFile() { ThreadPool.QueueUserWorkItem((object state) => { var fullFilename = Path.Combine(ContentPath, App.Self.Url.Split('/').Last()); if (File.Exists(fullFilename)) { File.Delete(fullFilename); } if (!File.Exists(fullFilename)) { var wc = new WebClient(); wc.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed); wc.DownloadFileAsync(new Uri(App.Self.Url), fullFilename); } else { using (var pool = new NSAutoreleasePool()) pool.InvokeOnMainThread(() => App.Self.DownloadProgress++); } }); }
public void LinkApp(object view) { using (NSAutoreleasePool pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread(() => { var account = DBAccountManager.SharedManager.LinkedAccount; if (account == null) { DBAccountManager.SharedManager.LinkFromController((UIViewController)view); } }); } }
/// <summary> /// Returns the last feed item only. /// </summary> /// <returns>The last feed.</returns> /// <param name="xmlStream">Xml stream.</param> public async void ReturnLastFeed(Stream xmlStream) { await Task.Delay(TimeSpan.FromMilliseconds(1)); Update lastFeed = new Update(); using (XmlReader myXMLReader = XmlReader.Create((xmlStream))) { while (myXMLReader.Read()) { while (myXMLReader.Name != "title") { myXMLReader.Read(); } var hTitle = myXMLReader.ReadElementContentAsString(); //feedHeader.title = hTitle; myXMLReader.Read(); var hLink = myXMLReader.ReadElementContentAsString(); //feedHeader.link = hLink; myXMLReader.Read(); var hDescription = myXMLReader.ReadElementContentAsString(); myXMLReader.Read(); var hLanguage = myXMLReader.ReadElementContentAsString(); myXMLReader.Read(); var hCopyright = myXMLReader.ReadElementContentAsString(); myXMLReader.Read(); var hPubdate = myXMLReader.ReadElementContentAsString(); while (myXMLReader.Name != "item") { myXMLReader.Read(); } while (myXMLReader.Read() && myXMLReader.Name != "rss") { if (myXMLReader.Name == "title" && myXMLReader.NodeType == XmlNodeType.Element) { var item = new Update(); var fTitle = myXMLReader.ReadElementContentAsString(); item.title = fTitle; myXMLReader.Read(); var fLink = myXMLReader.ReadElementContentAsString(); item.link = fLink; myXMLReader.Read(); var fDescription = myXMLReader.ReadElementContentAsString(); item.description = fDescription; myXMLReader.Read(); var fPubdate = myXMLReader.ReadElementContentAsString(); item.pubDate = fPubdate; lastFeed = item; break; } } break; } } //Done string lastTitle = NSUserDefaults.StandardUserDefaults.StringForKey("rssTitle"); if (string.IsNullOrEmpty(lastTitle) || lastTitle != lastFeed.title) { using (var pool = new NSAutoreleasePool()) { try { pool.InvokeOnMainThread(delegate { createRssPopup(lastFeed); }); } catch (Exception e) { Console.WriteLine("Error: " + e); } } } else { var newTime = DateTime.Now.ToLocalTime().ToString(); NSUserDefaults.StandardUserDefaults.SetString(newTime, "rssCheck"); } IsReadingXML = false; }
void Completed(object sender, AsyncCompletedEventArgs e) { using (var pool = new NSAutoreleasePool()) pool.InvokeOnMainThread(() => App.Self.DownloadProgress++); }
/// <summary> /// Checks if is available for monitoring /// </summary> /// <returns></returns> public bool AvailableForMonitoring() { bool retVal = false; RequestAlwaysAuthorization(); if (!CLLocationManager.LocationServicesEnabled) { string message = string.Format("{0} - {1}", CrossGeofence.Id, "You need to enable Location Services"); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } else if (CLLocationManager.Status == CLAuthorizationStatus.Denied || CLLocationManager.Status == CLAuthorizationStatus.Restricted) { string message = string.Format("{0} - {1}", CrossGeofence.Id, "You need to authorize Location Services"); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } else if (CLLocationManager.IsMonitoringAvailable(typeof(CLRegion))) { if (RequestNotificationPermission) { using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread(() => { var settings = UIUserNotificationSettings.GetSettingsForTypes( UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, new NSSet()); UIApplication.SharedApplication.RegisterUserNotificationSettings(settings); }); } } retVal = true; } else { string message = string.Format("{0} - {1}", CrossGeofence.Id, "Not available for monitoring"); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } return retVal; }
/// <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); }
void RequestAlwaysAuthorization() { if (!RequestLocationPermission) return; if (isPromptingLocationPermission) return; isPromptingLocationPermission = true; CLAuthorizationStatus status = CLLocationManager.Status; if(status ==CLAuthorizationStatus.AuthorizedWhenInUse || status == CLAuthorizationStatus.Denied) { string title = (status == CLAuthorizationStatus.Denied) ? "Location services are off" : "Background location is not enabled"; string message = "To use background location you must turn on 'Always' in the Location Services Settings"; using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread(() => { UIAlertView alertView = new UIAlertView(title, message, null, "Cancel", "Settings"); alertView.Clicked += (sender, buttonArgs) => { if (buttonArgs.ButtonIndex == 1) { // Send the user to the Settings for this app NSUrl settingsUrl = new NSUrl(UIApplication.OpenSettingsUrlString); UIApplication.SharedApplication.OpenUrl(settingsUrl); } isPromptingLocationPermission = false; }; alertView.Show(); }); } } else if (status == CLAuthorizationStatus.NotDetermined) { locationManager.RequestAlwaysAuthorization(); } }
private void ExecuteCommandThread() { using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread(delegate { if (Command.CanExecute(CommandParameter)) Command.Execute(CommandParameter); Animating = false; }); } }
/// <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); }
void HandleQuizCompleted (object sender, GetQuizCompletedEventArgs args) { bool error = ServiceAgent.HandleAsynchCompletedError (args, "GetQuiz"); using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread (delegate { Busy = false; if (error) return; Model.Quiz result = args.Result.ToLbkQuiz (); //result.Id = 14; _qvc = new QuizViewController (result); this.NavigationController.PushViewController (_qvc, true); }); } }
void HandleGetMenuLastUpdateCompleted (object sender, GetMenuLastUpdateCompletedEventArgs args) { bool error = ServiceAgent.HandleAsynchCompletedError (args, "GetMenuLastUpdate"); using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread (delegate { Busy = false; if (error) return; var updateDate = args.Result; this.Display(updateDate); }); } }