Exemplo n.º 1
0
 public void StopTimer()
 {
     if (timer != null) {
         if (timer.IsValid) timer.Invalidate();
         timer = null;
     }
 }
Exemplo n.º 2
0
		public override void ViewDidDisappear (bool animated)
		{
			base.ViewDidDisappear (animated);

			_autoRefreshTimer.Invalidate ();
			_autoRefreshTimer = null;
		}
Exemplo n.º 3
0
		public ClockTimer () : base()
		{
			outputString = DateTime.Now.ToString("hh:mm:ss");
			myTTimer = NSTimer.CreateRepeatingScheduledTimer (1,delegate { 
				outputString = DateTime.Now.ToString("hh:mm:ss");
			});
		}
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			sessionManager = new SessionManager ();
			sessionManager.StartRunning ();

			previewLayer = new AVCaptureVideoPreviewLayer (sessionManager.CaptureSession) {
				Frame = previewView.Bounds,
				LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill
			};

			if (previewLayer.Connection != null && previewLayer.Connection.SupportsVideoOrientation)
				previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft;
			previewView.Layer.AddSublayer (previewLayer);
			previewView.Layer.MasksToBounds = true;

			barcodeTargetLayer = new CALayer () {
				Frame = View.Layer.Bounds
			};
			View.Layer.AddSublayer (barcodeTargetLayer);

			synth = new Synth ();
			synth.LoadPreset (this);

			stepTimer = NSTimer.CreateRepeatingScheduledTimer (0.15, step);
		}
Exemplo n.º 5
0
        public new void DraggingEnded(UIScrollView scrollView, bool willDecelerate)
        {
            if (_tableView.ContentOffset.Y <= -65f) {

                _reloading = true;
                _tableView.ReloadData ();
                _refreshHeaderView.ToggleActivityView ();
                UIView.BeginAnimations ("ReloadingData");
                UIView.SetAnimationDuration (0.2);
                _tableView.ContentInset = new UIEdgeInsets (60f, 0f, 0f, 0f);
                UIView.CommitAnimations ();

                _nearbyViewController.SetNearbyBusStops();

                //ReloadTimer = NSTimer.CreateRepeatingScheduledTimer (new TimeSpan (0, 0, 0, 10, 0), () => dataSourceDidFinishLoadingNewData ());
                //_reloadTimer = NSTimer.CreateScheduledTimer (TimeSpan.FromSeconds (2f), delegate {
                    _reloadTimer = null;
                    _reloading = false;
                    //_refreshHeaderView.FlipImageAnimated (false);
                    _refreshHeaderView.ToggleActivityView ();
                    UIView.BeginAnimations ("DoneReloadingData");
                    UIView.SetAnimationDuration (0.3);
                    _tableView.ContentInset = new UIEdgeInsets (0f, 0f, 0f, 0f);
                    _refreshHeaderView.SetPullToUpdateStatus();
                    UIView.CommitAnimations ();
                    _refreshHeaderView.SetCurrentDate ();
                //});

            }

            _checkForRefresh = false;
        }
Exemplo n.º 6
0
		void CancelHoldTimer ()
		{
			if (holdTimer == null)
				return;
			holdTimer.Invalidate ();
			holdTimer = null;
		}
Exemplo n.º 7
0
 public void Stop()
 {
     if (this.timer != null) {
         this.timer.Invalidate ();
         this.timer = null;
     }
 }
Exemplo n.º 8
0
		void OnStartProgressTapped (object sender, EventArgs e)
		{
			standardProgressView.Progress = 0;
			bigRadialProgressView.Reset ();
			smallRadialProgressView.Reset ();
			tinyRadialProgressView.Reset ();

			if (timer != null) {
				timer.Invalidate ();
				timer = null;
			}

			// Start a timer to increment progress regularly until complete
			timer = NSTimer.CreateRepeatingScheduledTimer (1.0 / 30.0, () => {
				bigRadialProgressView.Value += 0.005f;
				smallRadialProgressView.Value += 0.005f;
				tinyRadialProgressView.Value += 0.005f;
				standardProgressView.Progress += 0.005f;

				if (bigRadialProgressView.IsDone) {
					timer.Invalidate ();
					timer = null;
				}
			});
		}
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			sessionManager = new SessionManager ();
			sessionManager.StartRunning ();

			previewLayer = new AVCaptureVideoPreviewLayer (sessionManager.CaptureSession) {
				Frame = previewView.Bounds,
				VideoGravity = AVLayerVideoGravity.ResizeAspectFill
			};

			if (previewLayer.Connection != null && previewLayer.Connection.SupportsVideoOrientation)
				previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft;
			previewView.Layer.AddSublayer (previewLayer);
			previewView.Layer.MasksToBounds = true;

			barcodeTargetLayer = new CALayer () {
				Frame = View.Layer.Bounds
			};
			View.Layer.AddSublayer (barcodeTargetLayer);

			synth = new Synth ();
			synth.LoadPreset (this);

			// the loop that continuously looks for barcodes to detect
			stepTimer = NSTimer.CreateScheduledTimer (0.15, this, new Selector ("step:"), null, true);
		}
Exemplo n.º 10
0
		public void Animate()
		{
			if (timer != null)
				timer.Invalidate();
			timer = NSTimer.CreateRepeatingScheduledTimer(ImageDuration, nextImage);
			timer.Fire();
		}
Exemplo n.º 11
0
        public override void AwakeFromNib()
        {
            base.AwakeFromNib ();
            playBtnBG = UIImage.FromFile ("images/play.png");
            pauseBtnBG = UIImage.FromFile ("images/pause.png");

            playButton.SetImage (playBtnBG, UIControlState.Normal);

            this.registerForBackgroundNotifications ();

            updateTimer = null;
            rewTimer = null;
            ffwTimer = null;

            duration.AdjustsFontSizeToFitWidth = true;
            currentTime.AdjustsFontSizeToFitWidth = true;
            progressBar.MinValue = 0.0f;

            // Load the the sample file, use mono or stero sample
            NSUrl fileURL = NSUrl.FromFilename (NSBundle.MainBundle.PathForResource ("sample" , @"m4a"));

            CreateNewPlayer ( fileURL);

            AudioSession.Initialize();

            NSError setCategoryError;
            AVAudioSession.SharedInstance ().SetCategory (new NSString (AVAudioSession.CategoryPlayback.ToString ()), out setCategoryError);
            AVAudioSession.SharedInstance ().SetActive (true, out setCategoryError);
            UIApplication.SharedApplication.BeginReceivingRemoteControlEvents ();

            if (setCategoryError != null)
                Console.WriteLine (@"Error setting category! {0}", setCategoryError);

            AudioSession.AddListener (AudioSessionProperty.AudioRouteChange, RouteChangeListener);
        }
Exemplo n.º 12
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
     
            /*
            var path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            path = System.IO.Path.Combine(path, "loop_stereo.aif"); // loop_mono.wav
            if (!System.IO.File.Exists(path))
                throw new ArgumentException("file not found; " + path);*/

            var url = MonoTouch.CoreFoundation.CFUrl.FromFile("loop_stereo.aif");
            _player = new ExtAudioFilePlayer(url);

            // setting audio session
            _slider.ValueChanged += new EventHandler(_slider_ValueChanged);
            _playButton.TouchDown += new EventHandler(_playButton_TouchDown);
            _stopButton.TouchDown += new EventHandler(_stopButton_TouchDown);

            _slider.MaxValue = _player.TotalFrames;

            _isTimerAvailable = true;
            _timer = NSTimer.CreateRepeatingTimer(TimeSpan.FromMilliseconds(100),
                delegate {
                    if (_isTimerAvailable)
                    {
                        long pos = _player.CurrentPosition;
                        _slider.Value = pos;
                        //System.Diagnostics.Debug.WriteLine("CurPos: " + _player.CurrentPosition.ToString());
                    }                    
                }
                );
            NSRunLoop.Current.AddTimer(_timer, "NSDefaultRunLoopMode");            
        }
        public void DraggingEnded(UIScrollView scrollView, bool willDecelerate)
        {
            if (_table.ContentOffset.Y <= -65f) {

                //ReloadTimer = NSTimer.CreateRepeatingScheduledTimer (new TimeSpan (0, 0, 0, 10, 0), () => dataSourceDidFinishLoadingNewData ());
                _reloadTimer = NSTimer.CreateScheduledTimer (TimeSpan.FromSeconds (2f), delegate {
                    // for this demo I cheated and am just going to pretend data is reloaded
                    // in real world use this function to really make sure data is reloaded

                    _reloadTimer = null;
                    Console.WriteLine ("dataSourceDidFinishLoadingNewData() called from NSTimer");

                    _reloading = false;
                    _refreshHeaderView.FlipImageAnimated (false);
                    _refreshHeaderView.ToggleActivityView ();
                    UIView.BeginAnimations ("DoneReloadingData");
                    UIView.SetAnimationDuration (0.3);
                    _table.ContentInset = new UIEdgeInsets (0f, 0f, 0f, 0f);
                    _refreshHeaderView.SetStatus (TableViewPullRefresh.RefreshTableHeaderView.RefreshStatus.PullToReloadStatus);
                    UIView.CommitAnimations ();
                    _refreshHeaderView.SetCurrentDate ();
                });

                _reloading = true;
                _table.ReloadData ();
                _refreshHeaderView.ToggleActivityView ();
                UIView.BeginAnimations ("ReloadingData");
                UIView.SetAnimationDuration (0.2);
                _table.ContentInset = new UIEdgeInsets (60f, 0f, 0f, 0f);
                UIView.CommitAnimations ();
            }

            _checkForRefresh = false;
        }
        public void StartTimer(CLLocationManager manager)
        {
            hasLastAttempt = false;

            Manager = manager;
            locationTimer = NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(30), TerminateLocationUpdate);
        }
Exemplo n.º 15
0
        public RootController()
            : base(new RootElement ("Netstat"))
        {
            Settings = Settings.Instance;

            section = new Section ();
            Root.Add (section);

            displayedEntries = new Dictionary<NetstatEntry,DateTime> ();

            RefreshRequested += (sender, e) => {
                Populate ();
                ReloadComplete ();
            };

            Settings.Modified += (sender, e) => InvokeOnMainThread (() => {
                displayedEntries.Clear ();
                Populate ();
            });

            timer = NSTimer.CreateRepeatingTimer (1.0, () => {
                if (View.Hidden || !Settings.AutoRefresh)
                    return;
                Populate ();
            });
            NSRunLoop.Main.AddTimer (timer, NSRunLoopMode.Default);
        }
        public void AnimateNextExpressionFrame()
        {
            this._expressionFrameTimer = null;

            NSDictionary frameDictionary = this._curFrameArray.ObjectAtIndex(this._curFrameIndex).CastTo<NSDictionary>();

            // Grab image and force draw.  Use cache to reduce disk hits
            NSString frameImageName = frameDictionary[kCharacterExpressionFrameImageFileNameKey].CastTo<NSString>();
            Id imageName = this._imageCache[frameImageName];
            if (imageName != null)
            {
                this._curFrameImage = imageName.CastTo<NSImage>();
            }
            else
            {
                this._curFrameImage = new NSImage(NSBundle.MainBundle.PathForResourceOfType(frameImageName, NSString.Empty));
                this._imageCache[frameImageName] = this._curFrameImage;
                this._curFrameImage.Release();
            }
            this.Display();

            // If there is more than one frame, then schedule drawing of the next and increment our frame index.
            if (this._curFrameArray.Count > 1)
            {
                this._curFrameIndex++;
                this._curFrameIndex %= this._curFrameArray.Count;
                this._expressionFrameTimer = NSTimer.ScheduledTimerWithTimeIntervalTargetSelectorUserInfoRepeats(frameDictionary[kCharacterExpressionFrameDurationKey].CastTo<NSNumber>().FloatValue,
                                                                                                                 this,
                                                                                                                 ObjectiveCRuntime.Selector("animateNextExpressionFrame"),
                                                                                                                 null,
                                                                                                                 false);
            }
        }
Exemplo n.º 17
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
     
			var url = MonoTouch.CoreFoundation.CFUrl.FromFile ("loop_stereo.aif");
			_player = new ExtAudioBufferPlayer (url);

			// setting audio session
			_slider.ValueChanged += new EventHandler (_slider_ValueChanged);

			_slider.MaxValue = _player.TotalFrames;

			_isTimerAvailable = true;
			_timer = NSTimer.CreateRepeatingTimer (TimeSpan.FromMilliseconds (100),
                delegate {
				if (_isTimerAvailable) {
					long pos = _player.CurrentPosition;
					_slider.Value = pos;
					_signalLevelLabel.Text = _player.SignalLevel.ToString ("0.00E0");
				}                    
			}
			);

			NSRunLoop.Current.AddTimer (_timer, NSRunLoopMode.Default);            
		}
		void UpdateUserInterface(NSTimer t)
		{
			WKInterfaceController.OpenParentApplication (new NSDictionary (), (replyInfo, error) => {
				if(error != null) {
					Console.WriteLine (error);
					return;
				}

				var status = (CLAuthorizationStatus)((NSNumber)replyInfo["status"]).UInt32Value;
				var longitude = ((NSNumber)replyInfo["lon"]).DoubleValue;
				var latitude = ((NSNumber)replyInfo["lat"]).DoubleValue;

				Console.WriteLine ("authorization status {0}", status);
				switch(status) {
					case CLAuthorizationStatus.AuthorizedAlways:
						SetCooridinate(longitude, latitude);
						HideWarning();
						break;

					case CLAuthorizationStatus.NotDetermined:
						SetNotAvailable();
						ShowWarning("Launch the iOS app first");
						break;

					case CLAuthorizationStatus.Denied:
						SetNotAvailable();
						ShowWarning("Enable Location Service on iPhone");
						break;

					default:
						throw new NotImplementedException();
				}
			});
		}
Exemplo n.º 19
0
		private void ExecuteTimer()
		{
			_Timer.Invalidate();
			_Timer.Dispose();		
			_Timer = null;

			_Action();
		}
 public void StopTimer()
 {
     if (locationTimer != null)
     {
         locationTimer.Invalidate();
     }
     locationTimer = null;
     Manager = null;
 }
Exemplo n.º 21
0
		private void KillTimer()
		{
			if (_Timer != null)
			{
				_Timer.Invalidate();
				_Timer.Dispose();
				_Timer = null;
			}
		}
Exemplo n.º 22
0
        public CustomAnnotationProvider(int pages)
            : base()
        {
            annotations = new PSPDFAnnotation[pages].ToList ();

            // add timer in a way so it works while we're dragging pages
            timer = NSTimer.CreateTimer (1, this, new Selector ("timerFired:"), null, true);
            NSRunLoop.Current.AddTimer (timer, NSRunLoopMode.Common);
        }
		public override void ViewDidAppear (bool animated)
		{
			base.ViewDidAppear (animated);

			#if __UNIFIED__
			timer = NSTimer.CreateScheduledTimer (1/30, this, new ObjCRuntime.Selector ("MoveCamera"), null, true);
			#else
			timer = NSTimer.CreateScheduledTimer (1/30, this, new MonoTouch.ObjCRuntime.Selector ("MoveCamera"), null, true);
			#endif
		}
Exemplo n.º 24
0
 public override void ViewDidLoad()
 {
     base.ViewDidLoad();
       countdown = OptionsRepository.GetOptions().Seconds;
       timerLabel.Text = countdown.ToString();
       if (cameraTimer == null)
       {
     cameraTimer = NSTimer.CreateRepeatingScheduledTimer(1.0, TimerFire);
       }
 }
Exemplo n.º 25
0
		protected override void Dispose (bool disposing)
		{
			disposed = true;
			if (beatTimer != null) {
				beatTimer.Dispose ();
				beatTimer = null;
			}
	
			base.Dispose (disposing);
		}
		public override void Awake (NSObject context)
		{
			base.Awake (context);

			timer = NSTimer.CreateRepeatingScheduledTimer (5, UpdateUserInterface);
			UpdateUserInterface (timer);

			// Configure interface objects here.
			Console.WriteLine ("{0} awake with context", this);
		}
Exemplo n.º 27
0
 public SocketScannerHelper()
 {
     if (MonoTouch.ObjCRuntime.Runtime.Arch == MonoTouch.ObjCRuntime.Arch.SIMULATOR)
         return;
     ScanApi = new ScanApiHelper ();
     ScanApi.Delegate = new ScanDelegate (this);
     ScanApi.Open ();
     timer = NSTimer.CreateRepeatingScheduledTimer (.2, () => {
         var r = ScanApi.DoScanApiReceive();
     });
 }
Exemplo n.º 28
0
 public void SetFadeTimer(NSTimer timer)
 {
     if (this.fadeTimer != timer)
     {
         if (this.fadeTimer != null)
         {
             this.fadeTimer.Invalidate();
             this.fadeTimer.SafeRelease();
         }
         this.fadeTimer = timer.SafeRetain();
     }
 }
Exemplo n.º 29
0
        public void DeactivateLoupe()
        {
            loopActivated = false;

            if (touchTimer != null)
            {
                touchTimer.Invalidate();
                touchTimer = null;
            }

            RemoveFromSuperview();
        }
Exemplo n.º 30
0
		public static void Initialize()
		{
			CoreLocationManager = new CLLocationManager();
			
			CoreLocationManager.StartUpdatingLocation();
			
			CoreLocationManager.UpdatedHeading += HandleCoreLocationManagerUpdatedHeading;
			CoreLocationManager.UpdatedLocation += HandleCoreLocationManagerUpdatedLocation;
			
			UpdateLocationTimer = NSTimer.CreateRepeatingTimer(TimeSpan.FromMinutes(1), InitializeLocationUpdate);
			UpdateHeadingTimer =NSTimer.CreateRepeatingTimer(TimeSpan.FromMinutes(1), InitializeHeadingUpdate);
		}
Exemplo n.º 31
0
        public NativeSnackBar Show()
        {
            SnackBarView = GetSnackBarView();

            SnackBarView.ParentView?.AddSubview(SnackBarView);
            SnackBarView.ParentView?.BringSubviewToFront(SnackBarView);

            SnackBarView.Setup();

            timer = NSTimer.CreateScheduledTimer(TimeSpan.FromMilliseconds(Duration), async t =>
            {
                if (TimeoutAction != null)
                {
                    await TimeoutAction();
                }
                Dismiss();
            });

            return(this);
        }
Exemplo n.º 32
0
        private void InitializeTimer()
        {
            const float updateTimerFrequency = 1f;

            using (var pool = new NSAutoreleasePool()) {
                // Every 1 sec we update game timer
                mTimer = NSTimer.CreateRepeatingScheduledTimer(updateTimerFrequency, delegate {
                    if (mIsPaused == false)
                    {
                        mCurrentTime = mCurrentTime.AddSeconds(updateTimerFrequency);

                        this.InvokeOnMainThread(() => {
                            LabelTime.Text = mCurrentTime.ToString("mm:ss");
                        });
                    }
                });

                NSRunLoop.Current.Run();
            }
        }
Exemplo n.º 33
0
        private async Task StopEventTimerAsync()
        {
            _eventTimer?.Invalidate();
            _eventTimer?.Dispose();
            _eventTimer = null;
            if (_eventBackgroundTaskId > 0)
            {
                UIApplication.SharedApplication.EndBackgroundTask(_eventBackgroundTaskId);
                _eventBackgroundTaskId = 0;
            }
            _eventBackgroundTaskId = UIApplication.SharedApplication.BeginBackgroundTask(() =>
            {
                UIApplication.SharedApplication.EndBackgroundTask(_eventBackgroundTaskId);
                _eventBackgroundTaskId = 0;
            });
            await _eventService.UploadEventsAsync();

            UIApplication.SharedApplication.EndBackgroundTask(_eventBackgroundTaskId);
            _eventBackgroundTaskId = 0;
        }
Exemplo n.º 34
0
 public override void TextDidChange(NSNotification notification)
 {
     try {
         Controller.HandleTextChanged();
     } catch (Exception ex) {
         Console.WriteLine();
     }
     if (changeThrottle != null)
     {
         changeThrottle.Invalidate();
     }
     changeThrottle = NSTimer.CreateScheduledTimer(0.3333, t => {
         try {
             changeThrottle = null;
             Controller.HandleThrottledTextChanged();
         } catch (Exception ex) {
             ShowError(ex);
         }
     });
 }
Exemplo n.º 35
0
        public void Run(double updatesPerSecond)
        {
            _openGLContext.SwapInterval = false;

            if (!_animating)
            {
                var timeout = new TimeSpan((long)(((1.0 * TimeSpan.TicksPerSecond) / updatesPerSecond) + 0.5));
                _animationTimer = NSTimer.CreateRepeatingScheduledTimer(timeout,
                                                                        delegate {
                    _openGLContext.MakeCurrentContext();
                    OnUpdateFrame();
                    OnRenderFrame();
                    _openGLContext.FlushBuffer();
                });

                NSRunLoop.Current.AddTimer(_animationTimer, NSRunLoopMode.Default);
                NSRunLoop.Current.AddTimer(_animationTimer, NSRunLoopMode.EventTracking);
            }
            _animating = true;
        }
Exemplo n.º 36
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            _player = new RemoteOutput();

            _playButton.TouchDown += new EventHandler(_playButton_TouchDown);
            _stopButton.TouchDown += new EventHandler(_stopButton_TouchDown);

            _playButton.Enabled = true;
            _stopButton.Enabled = false;

            _timer = NSTimer.CreateRepeatingTimer(TimeSpan.FromMilliseconds(200),
                                                  delegate
            {
                _label.Text = _player.SignalLevel.ToString("E");
            }
                                                  );
            NSRunLoop.Current.AddTimer(_timer, "NSDefaultRunLoopMode");
        }
 void HideUsingAnimation(bool animated)
 {
     // Fade out
     if (animated)
     {
         if (animated)
         {
             UIView.BeginAnimations(null);
             UIView.SetAnimationDuration(0.40);
             this.Alpha = .02f;
             NSTimer.CreateScheduledTimer(.4, AnimationFinished);
             UIView.CommitAnimations();
         }
         else
         {
             this.Alpha = 0.0f;
             this.Done();
         }
     }
 }
Exemplo n.º 38
0
        public void StartWorker()
        {
            if (WorkerTimer != null)
            {
                return;
            }

            var delay = TimeSpan.FromMilliseconds(_parentViewController.ScanningOptions.DelayBetweenAnalyzingFrames);

            if (firstTimeWorker)
            {
                delay           = TimeSpan.FromMilliseconds(_parentViewController.ScanningOptions.InitialDelayBeforeAnalyzingFrames);
                firstTimeWorker = false;
            }

            WorkerTimer = NSTimer.CreateRepeatingTimer(delay, delegate {
                Worker();
            });
            NSRunLoop.Current.AddTimer(WorkerTimer, NSRunLoopMode.Default);
        }
Exemplo n.º 39
0
        private void ElevationSlider_ValueChanged(object sender, EventArgs e)
        {
            if (elevationTimer == null && isContinuous)
            {
                // Use a timer to continuously update elevation while the user is interacting (joystick effect).
                elevationTimer = new NSTimer(NSDate.Now, 0.1, true, (timer) =>
                {
                    // Calculate the altitude offset
                    var newValue = locationSource.AltitudeOffset += JoystickConverter(elevationSlider.Value);

                    // Set the altitude offset on the location data source.
                    locationSource.AltitudeOffset = newValue;

                    // Update the label
                    elevationLabel.Text = $"Elevation: {(int)locationSource.AltitudeOffset}m";
                });

                NSRunLoop.Main.AddTimer(elevationTimer, NSRunLoopMode.Default);
            }
        }
Exemplo n.º 40
0
        /// <summary>
        /// Schedule the specified state, dueTime and action.
        /// </summary>
        /// <param name="state">State.</param>
        /// <param name="dueTime">Due time.</param>
        /// <param name="action">Action.</param>
        /// <typeparam name="TState">The 1st type parameter.</typeparam>
        public IDisposable Schedule <TState>(TState state, TimeSpan dueTime, Func <IScheduler, TState, IDisposable> action)
        {
            var  innerDisp   = Disposable.Empty;
            bool isCancelled = false;

            var timer = NSTimer.CreateScheduledTimer(dueTime, _ =>
            {
                if (!isCancelled)
                {
                    innerDisp = action(this, state);
                }
            });

            return(Disposable.Create(() =>
            {
                isCancelled = true;
                timer.Invalidate();
                innerDisp.Dispose();
            }));
        }
Exemplo n.º 41
0
        /// <summary>
        /// Animates a fade-in where the view starts hidden and fades visible.
        /// </summary>
        /// <param name="views">A list of views to animate.</param>
        /// <param name="duration">The duration for the animation.</param>
        /// <param name="delay">An optional delay before starting the animation.</param>
        /// <param name="animationOptions">The animation options, the default is a cross dissolve transition.</param>
        public static void AnimateFadeIn(
            IEnumerable <UIView> views,
            double duration,
            double delay = 0,
            UIViewAnimationOptions animationOptions = UIViewAnimationOptions.TransitionCrossDissolve)
        {
            if (delay > 0)
            {
                foreach (UIView view in views)
                {
                    view.Alpha = 0;
                }

                NSTimer.CreateScheduledTimer(delay, timer => ViewAnimation.AnimateFadeIn(views, duration, animationOptions));
            }
            else
            {
                ViewAnimation.AnimateFadeIn(views, duration, animationOptions);
            }
        }
Exemplo n.º 42
0
        //for test
        void AddTimer()
        {
            var     timeout      = new TimeSpan((long)(((0.1 * TimeSpan.TicksPerSecond) / 1) + 0.0));
            int     progress     = 10;
            long    downloadSize = 0;
            NSTimer timer        = NSTimer.CreateRepeatingScheduledTimer(timeout,
                                                                         delegate {
                if (progress <= 100)
                {
                    //Console.WriteLine("{0}",progress);
                    UpdateDownloadProgress(progress, downloadSize);
                    progress += 10;
                }
                else
                {
                }
            });

            NSRunLoop.Current.AddTimer(timer, NSRunLoopMode.Default);
        }
Exemplo n.º 43
0
        public void ShowSingleWithTimeout(string message, int seconds)
        {
            UIApplication.SharedApplication.InvokeOnMainThread(() =>
            {
                UIAlertView alert = new UIAlertView()
                {
                    Message = message,
                    Alpha   = 1.0f
                };
                NSTimer tmr;
                alert.Show();

                tmr = NSTimer.CreateTimer(seconds, delegate
                {
                    alert.DismissWithClickedButtonIndex(0, true);
                    alert = null;
                });
                NSRunLoop.Main.AddTimer(tmr, NSRunLoopMode.Common);
            });
        }
Exemplo n.º 44
0
        // Slowly turn off the audio
        public void Stop()
        {
            if (player == null)
            {
                return;
            }

            float volume = player.Volume;

            timer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromMilliseconds(100), delegate {
                volume       -= 0.05f;
                player.Volume = volume;
                if (volume <= 0.1)
                {
                    lastTime = player.CurrentTime;
                    player.Stop();
                    timer.Invalidate();
                }
            });
        }
Exemplo n.º 45
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            switch (counter % 2)
            {
            case 0:
                View.BackgroundColor = UIColor.Yellow;
                break;

            default:
                View.BackgroundColor = UIColor.LightGray;
                break;
            }
#if XAMCORE_2_0
            NSTimer.CreateScheduledTimer(0.01, (v) => action());
#else
            NSTimer.CreateScheduledTimer(0.01, () => action());
#endif
        }
Exemplo n.º 46
0
        private void PresentDices(PresentationViewController presentationViewController)
        {
            var count  = 200;
            var spread = 6;

            // drop rigid bodies cubes
            var intervalTime   = 5.0 / count;
            var remainingCount = count;

            Timer = NSTimer.CreateRepeatingTimer(intervalTime, delegate(NSTimer obj) {
                if (Step > 4)
                {
                    Timer.Invalidate();
                    return;
                }

                SCNTransaction.Begin();

                var worldPos = GroundNode.ConvertPositionToNode(new SCNVector3(0, 30, 0), null);

                var dice = CreateBlock(worldPos, new SCNVector3(1.5f, 1.5f, 1.5f));

                //add to scene
                ((SCNView)presentationViewController.View).Scene.RootNode.AddChildNode(dice);

                dice.PhysicsBody.Velocity        = new SCNVector3(RandFloat(-spread, spread), -10, RandFloat(-spread, spread));
                dice.PhysicsBody.AngularVelocity = new SCNVector4(RandFloat(-1, 1), RandFloat(-1, 1), RandFloat(-1, 1), RandFloat(-3, 3));

                SCNTransaction.Commit();

                Dices.Add(dice);

                // ensure we stop firing
                if (--remainingCount < 0)
                {
                    Timer.Invalidate();
                }
            });

            NSRunLoop.Current.AddTimer(Timer, NSRunLoopMode.Default);
        }
Exemplo n.º 47
0
        private void setTimer()
        {
            NSTimer.CreateScheduledTimer(new TimeSpan(0, 0, 10), delegate
            {
                try{
                    if (CurrentPage - 1 < 0)
                    {
                        CurrentPage = 0;
                    }
                    if (CurrentPage == 5)
                    {
                        CurrentPage = 0;
                    }

                    double fromPage = CurrentPage - 1;
                    var toPage      = CurrentPage;


                    var pageOffset = sramdom.Frame.Width * toPage;
                    if (fromPage > toPage)
                    {
                        pageOffset = sramdom.ContentOffset.X - sramdom.Frame.Width;
                    }
                    PointF p = new PointF(pageOffset, 0);
                    sramdom.SetContentOffset(p, true);

                    CurrentPage++;
                }
                catch {
                    var toPage     = 0;
                    var pageOffset = sramdom.Frame.Width * toPage;

                    pageOffset = sramdom.ContentOffset.X - sramdom.Frame.Width;
                    PointF p   = new PointF(pageOffset, 0);
                    sramdom.SetContentOffset(p, true);
                    CurrentPage = 1;
                }

                setTimer();
            });
        }
Exemplo n.º 48
0
        public void Init()
        {
            if (store != null)
            {
                return;
            }
            DBError error;

            store = DBDatastore.OpenDefaultStore(DBAccountManager.SharedManager.LinkedAccount, out error);
            DBError error1;
            var     sync = store.Sync(out error1);

            store.AddObserver(store, () => {
                Console.Write("store observer ");

                DBError error2;
                store.Sync(out error2);                 // needed?

                var table   = store.GetTable(tableName);
                var results = table.Query(null, out error);

                Console.WriteLine(results.Length);

                ProccessResults(results);
            });


            // TIMER TO AUTOUPDATE
            AutoUpdating = true;
            store.BeginInvokeOnMainThread(() => {
                timer = NSTimer.CreateRepeatingScheduledTimer(2, () => {
                    if (!AutoUpdating)
                    {
                        return;
                    }
                    //Console.WriteLine("AutoUpdating"); // SPAM
                    DBError error3;
                    store.Sync(out error3);
                });
            });
        }
Exemplo n.º 49
0
        protected override void Dispose(bool disposing)
        {
            if (_CheckmarkImage != null)
            {
                _CheckmarkImage.Dispose();
            }

            if (_Indicator != null)
            {
                _Indicator.RemoveFromSuperview();
                _Indicator = null;
            }

            RemoveFromSuperview();

            if (_Label != null)
            {
                _Label.Dispose();
                _Label = null;
            }

            if (_DetailsLabel != null)
            {
                _DetailsLabel.Dispose();
                _DetailsLabel = null;
            }

            if (_GraceTimer != null)
            {
                _GraceTimer.Dispose();
                _GraceTimer = null;
            }

            if (_MinShowTimer != null)
            {
                _MinShowTimer.Dispose();
                _MinShowTimer = null;
            }

            base.Dispose(disposing);
        }
Exemplo n.º 50
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            TextView = new UITextView(View.Bounds);
            TextView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleHeight;
            TextView.Changed         += (sender, e) => {
                if (WriteTimer != null)
                {
                    WriteTimer.Invalidate();
                }
                WriteTimer = NSTimer.CreateScheduledTimer(3, this, new MonoTouch.ObjCRuntime.Selector("saveChanges"), null, false);
            };
            View.AddSubview(TextView);
            ActivityIndicator = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.Gray);
            RectangleF frame = ActivityIndicator.Bounds;

            frame.X = (float)Math.Floor(View.Bounds.Size.Width / 2 - frame.Size.Width / 2);
            frame.Y = (float)Math.Floor(View.Bounds.Size.Height / 2 - frame.Size.Height / 2);
            ActivityIndicator.Frame = frame;
            View.AddSubview(ActivityIndicator);
        }
Exemplo n.º 51
0
        void ShowAlert(string message, double seconds)
        {
            var alert = UIAlertController.Create(null, message, UIAlertControllerStyle.ActionSheet);

            var alertDelay = NSTimer.CreateScheduledTimer(seconds, obj =>
            {
                DismissMessage(alert, obj);
            });

            var viewController = UIApplication.SharedApplication.KeyWindow.RootViewController;

            while (viewController.PresentedViewController != null)
            {
                viewController = viewController.PresentedViewController;
            }
            viewController.PresentViewController(alert, true, () =>
            {
                UITapGestureRecognizer tapGesture = new UITapGestureRecognizer(_ => DismissMessage(alert, null));
                alert.View.Superview?.Subviews[0].AddGestureRecognizer(tapGesture);
            });
        }
        public override void TouchesBegan(NSSet touches, UIEvent evt)
        {
            if (trackedTouch == null)
            {
                trackedTouch     = (UITouch)touches.FirstOrDefault();
                initialTimestamp = trackedTouch.Timestamp;

                if (!IsForPencil)
                {
                    BeginIfNeeded(null);
                }
                fingerStartTimer = NSTimer.CreateScheduledTimer(cancellationTimeInterval, BeginIfNeeded);
            }
            if (Append(Touches(touches), evt))
            {
                if (IsForPencil)
                {
                    State = Began;
                }
            }
        }
        //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        public override void ViewDidLoad()
        {
            UpdateViewValues();

            Title = "Сервисный инцидент";

            ConfirmButton.TitleLabel.LineBreakMode = UILineBreakMode.WordWrap;
            ConfirmButton.TitleLabel.Lines         = 2;
            ConfirmButton.TitleLabel.TextAlignment = UITextAlignment.Center;

            RejectButton.TitleLabel.LineBreakMode = UILineBreakMode.WordWrap;
            RejectButton.TitleLabel.Lines         = 2;
            RejectButton.TitleLabel.TextAlignment = UITextAlignment.Center;

            CommentField.Layer.BorderColor = UIColor.LightGray.CGColor;
            CommentField.Layer.BorderWidth = 1f;

            SetLayout();

            timer = NSTimer.CreateRepeatingScheduledTimer(0.1, delegate { CheckNewData(); });
        }
Exemplo n.º 54
0
        // Update countdown timer.
        void UpdateText(NSTimer timer)
        {
            var gNodes = gameNodes.Value;

            gNodes.CountdownLabel.Text = countdown.ToString();
            sceneInterface.Playing     = true;
            sceneInterface.Playing     = false;
            countdown -= 1;

            if (countdown < 0)
            {
                gNodes.CountdownLabel.FontColor = GameColors.Danger;
                textUpdateTimer?.Invalidate();
                return;
            }

            if (countdown < 10)
            {
                gNodes.CountdownLabel.FontColor = GameColors.Warning;
            }
        }
Exemplo n.º 55
0
        public void StartRecording(UIButton button)
        {
            button.Enabled = false;

            _recordingWhisper = new Whisper();
            _db.Insert(_recordingWhisper);
            _recordingWhisper.StartRecording();

            BeginInvokeOnMainThread(() => {
                recordProgress.Hidden   = false;
                recordProgress.Progress = 0f;
                button.SetTitle("Stop", UIControlState.Normal);

                startedRecording = DateTime.Now;
                timer            = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(0.1), delegate {
                    RecordingTimer(button);
                });

                button.Enabled = true;
            });
        }
Exemplo n.º 56
0
        public void ShowToast(string message)
        {
            UIApplication.SharedApplication.InvokeOnMainThread(() =>
            {
                var alert = new UIAlertView()
                {
                    Message = message,
                    Alpha   = 1.0f
                };
                alert.Frame = new CoreGraphics.CGRect(alert.Frame.X, UIScreen.MainScreen.Bounds.Y * 0.7f, alert.Frame.Width, alert.Frame.Height);
                NSTimer tmr;
                alert.Show();

                tmr = NSTimer.CreateTimer(1.5, delegate
                {
                    alert.DismissWithClickedButtonIndex(0, true);
                    alert = null;
                });
                NSRunLoop.Main.AddTimer(tmr, NSRunLoopMode.Common);
            });
        }
Exemplo n.º 57
0
        protected virtual void Dispose(bool disposing)
        {
            disposed = true;

            if (!disposing)
            {
                return;
            }

            if (Peripheral.Delegate != null)
            {
                Peripheral.Delegate.Dispose();
                Peripheral.Delegate = null;
            }

            if (beatTimer != null)
            {
                beatTimer.Dispose();
                beatTimer = null;
            }
        }
Exemplo n.º 58
0
        void fire(NSTimer pTimer)
        {
            var nowChangeCount = this.pasteboard.ChangeCount;

            if (nowChangeCount == this.preChangeCount)
            {
                return;
            }

            this.preChangeCount = nowChangeCount;

            var nowString = this.pasteboard.GetStringForType(NSPasteboard.NSPasteboardTypeString);

            if (nowString == this.preString)
            {
                return;
            }

            this.preString = nowString;
            this.handler(nowString);
        }
        private void ShowAlert(string message, double seconds)
        {
            this.alertDelay = NSTimer.CreateScheduledTimer(seconds, (obj) =>
            {
                this.DismissMessage();
            });

            this.alert = UIAlertController.Create(null, null, UIAlertControllerStyle.ActionSheet);

            var messageAttributes = new UIStringAttributes
            {
                ForegroundColor = UIColor.White,
            };

            var subView = this.alert.View.Subviews.First().Subviews.First().Subviews.First();

            subView.BackgroundColor = Color.FromHex(DefaultBackgroundColor).ToUIColor();

            alert.SetValueForKey(new NSAttributedString(message, messageAttributes), new NSString("attributedMessage"));
            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(this.alert, true, null);
        }
Exemplo n.º 60
0
            public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action <UNNotificationPresentationOptions> completionHandler)
            {
                // Timer here for a timeout since no Toast Dismissed Event (7 seconds til auto dismiss)
                var timer = NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(7), (nsTimer) =>
                {
                    _action(_id, new NotificationResult()
                    {
                        Action = NotificationAction.Timeout
                    });

                    if (_cancel) // Clear notification from list
                    {
                        UNUserNotificationCenter.Current.RemoveDeliveredNotifications(new string[] { _id });
                    }

                    nsTimer.Invalidate();
                });

                // Shows toast on screen
                completionHandler(UNNotificationPresentationOptions.Alert);
            }