protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            var view = new LinearLayout(this)
            {
                LayoutParameters = new LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent),
                Orientation      = Orientation.Vertical
            };

            button = new Button(this)
            {
                Text = "Click me and wait for crash"
            };
            view.AddView(button, new LayoutParams(LayoutParams.MatchParent, LayoutParams.WrapContent));
            SetContentView(view);

            toRepeat = LoadHttpPage;

            button.Click += delegate
            {
                handler.Post(toRepeat);
                handler.PostDelayed(toRepeat, 50);
                handler.PostDelayed(toRepeat, 100);
                button.Text    = "...";
                button.Enabled = false;
            };
        }
 public void OnClick(View v)
 {
     Handler h = new Handler();
     h.Post(() => {
         this.Img.StartAnimation(this.AniSet);
     });
 }
Beispiel #3
0
 protected void RunOnMainThread(Action action)
 {
     Handler handler = new Handler(Looper.MainLooper);
     handler.Post(action);
     handler.Dispose();
     handler = null;
 }
Beispiel #4
0
		private void Peer_PeerConnected (object sender, PeerConnectedEventArgs args)
		{
			using (var h = new Handler (Looper.MainLooper))
				h.Post (() => {
					textView.Text = args.PeerId;
				});
		}
		private void CreateNotifications(Context context, string action, bool isMessageNeeded = true, bool isToastNeeded = true)
		{
			#if DEBUG
			try {
				if (isMessageNeeded)
				{
					Notification notification = new Notification.Builder(context)
						.SetContentTitle ("BluetoothNotify intent received " + action)
						.SetContentText ("message sent at" + System.DateTime.Now.ToLongTimeString ())
						.SetSmallIcon (Resource.Drawable.icon)
						.Build ();

					NotificationManager nMgr = (NotificationManager)context.GetSystemService (Android.Content.ContextWrapper.NotificationService);
					nMgr.Notify (0, notification);
				}

				if (isToastNeeded)
				{
					var myHandler = new Handler ();
					myHandler.Post (() =>  {
						Toast.MakeText (context, "BluetoothNotify intent received " + action, ToastLength.Long).Show ();
					});
				}
				
			} catch (Exception ex) {
				Log.Info ("com.tarabel.bluetoothnotify", "CreateNotification error in IntentReceiver " + ex.ToString());
			}
			#endif
		}
        public void BeginGeofencing(object sender, EventArgs eventArgs)
        {
            if (!apiClient.IsConnected) {
                var myHandler = new Handler ();
                myHandler.Post (() => {
                    Android.Widget.Toast.MakeText (this, "Google API Not Connected. Try Again.", Android.Widget.ToastLength.Long).Show ();
                });
                return;
            }

            try {
                if (connectedGeofences.Count >= 1) {
                    LocationServices.GeofencingApi.AddGeofences(apiClient, getGeofencingRequest(), getGeofencePendingIntent()).SetResultCallback(this);
                    string geofenceAnnounce = "Geofences Active At The Following Locations:\n";
                    foreach (ROMPGeofence geofName in connectedGeofences) {
                        geofenceAnnounce += geofName.Id + "\n";
                    }
                    var myHandler = new Handler ();
                    myHandler.Post (() => {
                        Android.Widget.Toast.MakeText (this, geofenceAnnounce, Android.Widget.ToastLength.Long).Show ();
                    });
                    FindViewById<Button>(Resource.Id.btnBegin).Visibility = ViewStates.Invisible;
                    FindViewById<TextView>(Resource.Id.lblConfirm).SetText("A record that you have checked-in will be made in the log of your education activity for this ROMP rotation when this device enters a 1km radius surrounding the facility of your ROMP rotation.", TextView.BufferType.Normal);
                    geofenceRequestIntent = PendingIntent.GetService (this, 0,
                        new Intent (this, Java.Lang.Class.FromType (typeof(GeofenceTransitionsIntentService))),
                        PendingIntentFlags.UpdateCurrent);
                } else {
                    FindViewById<Button>(Resource.Id.btnBegin).Visibility = ViewStates.Invisible;
                    FindViewById<TextView>(Resource.Id.lblConfirm).SetText("No Rotations Available, Please Try Within Your Scheduled Rotation Dates", TextView.BufferType.Normal);
                }
            } catch (SecurityException securityEx) {
                logSecurityException (securityEx);
            }
        }
		protected override void OnLayout (bool changed, int l, int t, int r, int b)
		{
			using (var h = new Handler (Looper.MainLooper)) {
				h.Post (() => {
					double width = base.Context.FromPixels ((double)(r - l));
					double height = base.Context.FromPixels ((double)(b - t));
					var size = new Size (width, height);

					var msw = MeasureSpec.MakeMeasureSpec (r - l, MeasureSpecMode.Exactly);
					var msh = MeasureSpec.MakeMeasureSpec (b - t, MeasureSpecMode.Exactly);
					_nativeView.Measure (msw, msh);
					_nativeView.Layout (0, 0, r - l, b - t);

					//			if (size != _previousSize) {
					var layout = _viewCell.View as Layout<Xamarin.Forms.View>;
					if (layout != null) {
						layout.Layout (new Rectangle (0, 0, width, height));
						layout.ForceLayout ();
						FixChildLayouts (layout);
						_isLaidOut = true;
					}
					_previousSize = size;
				});
			}
			//			}
		}
		public void Update (object bindingContext)
		{
			using (var h = new Handler (Looper.MainLooper)) {
				h.Post (() => {
					_viewCell.BindingContext = bindingContext;
				});
			}
		}
		private void StartPlayingHandler()
		{
			var handler = new Handler();
			var runnable = new Runnable(() => { handler.Post(OnPlaying); });
			if (!_executorService.IsShutdown)
			{
				_scheduledFuture = _executorService.ScheduleAtFixedRate(runnable, 100, 1000, TimeUnit.Milliseconds);
			}
		}
Beispiel #10
0
 public void Invoke(Action action)
 {
     //Another method
     //http://stackoverflow.com/questions/11123621/running-code-in-main-thread-from-another-thread
     var l = Android.OS.Looper.MainLooper; //Previously Context.GetMainLooper()
     Handler mainHandler = new Handler(l);
     Runnable myRunnable = new Runnable(action);
     mainHandler.Post(myRunnable);
 }
        protected override void OnCreate(Bundle bundle)
        {
            RequestWindowFeature(WindowFeatures.NoTitle);
            base.OnCreate (bundle);
            SetContentView (Resource.Layout.ChooseMode);
            try {
                string sessionKey = Intent.GetStringExtra ("SessionKey");
                int groupID = Intent.GetIntExtra ("GroupID", 0);
                int userID = Intent.GetIntExtra ("UserID", 0);
                var locSvc = new ROMPLocation ();
                Button button = FindViewById<Button> (Resource.Id.btnChoose);
                CheckBox cbpassive = FindViewById<CheckBox> (Resource.Id.cbPassive);
                CheckBox cbactive = FindViewById<CheckBox> (Resource.Id.cbActive);

                cbpassive.Click += (o, e) => {
                    if (cbactive.Checked) {
                        cbactive.Checked = false;
                    }
                };

                cbactive.Click += (o, e) => {
                    if (cbpassive.Checked) {
                        cbpassive.Checked = false;
                    }
                };

                button.Click += delegate {
                    if (cbactive.Checked) {
                        var nextActivity = new Intent(this, typeof(CheckInActivity));
                        nextActivity.PutExtra("SessionKey", sessionKey);
                        nextActivity.PutExtra("GroupID", groupID);
                        nextActivity.PutExtra("UserID", userID);
                        StartActivity(nextActivity);
                        Finish();
                    } else if (cbpassive.Checked) {
                        var nextActivity = new Intent(this, typeof(CheckInPassiveActivity));
                        nextActivity.PutExtra("SessionKey", sessionKey);
                        nextActivity.PutExtra("GroupID", groupID);
                        nextActivity.PutExtra("UserID", userID);
                        StartActivity(nextActivity);
                        Finish();
                    } else {
                        string errmsg = "Please choose a check in method before proceeding.";
                        var myHandler = new Handler();
                        myHandler.Post(() => {
                            Toast.MakeText(this, errmsg, ToastLength.Short).Show();
                        });
                    }
                };
            } catch (Exception e) {
                var myHandler = new Handler();
                myHandler.Post(() => {
                    Android.Widget.Toast.MakeText(this, e.Message, Android.Widget.ToastLength.Long).Show();
                });
                System.Diagnostics.Debug.Write (e.Message);
            }
        }
Beispiel #12
0
        private Task LoadThumbnail(GalleryMediaModel model)
        {
            return(Task.Run(() =>
            {
                var thumbnail = MediaStore.Images.Thumbnails.GetThumbnail(Context.ContentResolver, model.Id, ThumbnailKind.MiniKind, _options);
                if (thumbnail == null || _model == null || model.Id != _model.Id)
                {
                    return;
                }

                if (model.Orientation == 0)
                {
                    _handler.Post(() =>
                    {
                        if (_model == null || model.Id != _model.Id)
                        {
                            return;
                        }

                        BitmapUtils.ReleaseBitmap(Drawable);
                        SetImageBitmap(thumbnail);
                    });
                    return;
                }

                var matrix = new Matrix();
                matrix.PostRotate(model.Orientation);
                var oriThumbnail = Bitmap.CreateBitmap(thumbnail, 0, 0, thumbnail.Width, thumbnail.Height, matrix, false);

                BitmapUtils.ReleaseBitmap(thumbnail);

                _handler.Post(() =>
                {
                    if (_model == null || model.Id != _model.Id)
                    {
                        return;
                    }

                    BitmapUtils.ReleaseBitmap(Drawable);
                    SetImageBitmap(oriThumbnail);
                });
            }));
        }
 /// <summary>This method helps to fit a column.</summary>
 /// <remarks>
 /// This method helps to fit a column. it will be called when TableView is scrolled on
 /// horizontally.
 /// </remarks>
 public virtual void FitWidthSize(int position, bool scrollingLeft)
 {
     FitSize(position, IgnoreLeft, false);
     if (mNeedSetLeft & scrollingLeft)
     {
         // Works just like invoke later of swing utils.
         Android.OS.Handler handler = new Android.OS.Handler();
         handler.Post(new _Runnable_144(this));
     }
 }
		public GridViewCellContainer (Context context, FastGridCell fastGridCell, global::Android.Views.View parent, Size initialCellSize) : base (context)
		{
			using (var h = new Handler (Looper.MainLooper)) {
				h.Post (() => {
					_parent = parent;
					_viewCell = fastGridCell;
					fastGridCell.PrepareCell (initialCellSize);
//					_viewCell.View.BackgroundColor = Xamarin.Forms.Color.Green;
					var renderer = fastGridCell.View.GetOrCreateRenderer ();
					_nativeView = renderer.ViewGroup;
//					SetBackgroundColor (Android.Graphics.Color.Yellow);
					AddView (_nativeView);
				});
			}

		}
 public override void Send(SendOrPostCallback d, object state)
 {
     var looper = Looper.MainLooper;
     if (Looper.MyLooper() == looper) {
         d (state);
         return;
     }
     var m = new ManualResetEvent (false);
     using (Handler h = new Handler (looper)) {
         h.Post (() => {
             d (state);
             m.Set ();
         });
     }
     m.WaitOne ();
 }
        protected override void OnHandleIntent(Intent intent)
        {
            // Can use intent to pass data to the service.
            var val = intent.GetStringExtra(IntentValueKey);

            // IntentService uses queued worker threads. To do something on the UI we must invoke on the main thread.
            var handler = new Handler(Looper.MainLooper);
            handler.Post(() => {
                Toast.MakeText(this, $"OnHandleIntent({val})", ToastLength.Long).Show();
            });

            for(int i = 1; i < 20; i++)
            {
                MainActivity.L($"Processing...{i}");
                Thread.Sleep(1000);
            }
        }
		void CreateNotifications(string status)
		{
			#if DEBUG
				Notification notification = new Notification.Builder (this)
				.SetContentTitle ("BluetoothLowEnergySearchService " + status)
				.SetContentText ("message sent at" + System.DateTime.Now.ToLongTimeString ())
				.SetSmallIcon (Resource.Drawable.icon)
				.Build ();

			NotificationManager nMgr = (NotificationManager)GetSystemService (NotificationService);
			nMgr.Notify (0, notification);

			var myHandler = new Handler ();
			myHandler.Post (() =>  {
				Toast.MakeText (this, "BluetoothLowEnergySearchService "+ status, ToastLength.Long).Show ();
			});
			#endif
		}
		public List<string> GetDeviceList(Context context)
		{
			
			List<string> result = new List<string> ();

			// Get local Bluetooth adapter
			BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;

			// If the adapter is null, then Bluetooth is not supported
			if (bluetoothAdapter == null) {
				var myHandler = new Handler ();
				myHandler.Post (() =>  {
					Toast.MakeText (context, "Bluetooth is not available", ToastLength.Long).Show ();
				});
				return result;
			}

			// If bluetooth is not enabled, ask to enable it
			if (!bluetoothAdapter.IsEnabled)
			{
				var myHandler = new Handler ();
				myHandler.Post (() =>  {
					Toast.MakeText (context, "Bluetooth is not enabled, please enable it", ToastLength.Long).Show ();
				});
				var enableBtIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
			}

			// Get connected devices
			var listOfDevices = bluetoothAdapter.BondedDevices;
			if (listOfDevices.Count > 0)
			{
				foreach (var bluetoothDevice in listOfDevices)
				{
					if (!result.Contains(bluetoothDevice.Name + ":" + bluetoothDevice.Address))
						result.Add(bluetoothDevice.Name + ":" + bluetoothDevice.Address);
				}
			}

			return result;
		}
 public void OnResult(Java.Lang.Object statusRaw)
 {
     var status = statusRaw.JavaCast<Statuses>();
     if (status.IsSuccess) {
         var myHandler = new Handler ();
         myHandler.Post (() => {
             Android.Widget.Toast.MakeText (this, "Geofencing Started.", Android.Widget.ToastLength.Long).Show ();
         });
     } else {
         var myHandler = new Handler ();
         myHandler.Post (() => {
             Android.Widget.Toast.MakeText (this, "Error Starting Geofencing.", Android.Widget.ToastLength.Long).Show ();
         });
     }
 }
 private void ImageHelperOnImageChanged(object sender, MvxValueEventArgs<Bitmap> mvxValueEventArgs)
 {
     using (var h = new Handler(Looper.MainLooper)) h.Post(() => { this.SetImageBitmap(mvxValueEventArgs.Value); });
 }
Beispiel #21
0
 /// <summary>
 /// Invoke in UI thread.
 /// </summary>
 public void BeginInvoke(Delegate d, params object[] args)
 {
     var h = new Handler(Looper.MainLooper);
     h.Post(() => d.DynamicInvoke(args));
 }
Beispiel #22
0
 /// <summary>
 /// Invoke in UI thread.
 /// </summary>
 public void BeginInvoke(Action a)
 {
     var h = new Handler(Looper.MainLooper);
     h.Post(a);
 }
Beispiel #23
0
		void playSound(object sender, EventArgs e)
		{
			if (!isOnline ()) {
				var myHandler = new Handler ();
				myHandler.Post(()=>{
					Toast.MakeText (this, "Sin Conexión", ToastLength.Short).Show();
				});
				return;
			}

			var item = sender as ImageIconMap;
			vm._currentUnidad = _currentUnidad;
			vm._currentCurso = _currentCurso;
			vm._currentSection = item.index;

			if (_playerOn) {
				player.Stop ();

				if (_currentItemPlayer == item.index) {
					item.SetImageBitmap (lo.iconPlay);
					_playerOn = false;
					return;
				}

			}

			if (_currentItemPlayer != -1) {
				lo._listIconMap [_currentItemPlayer].SetImageBitmap (lo.iconPlay);
			}

			item.SetImageBitmap (pausePlayer);
			_currentItemPlayer = item.index;

			StartPlayer (lo._listUnidades[item.index].Description, item);
		}
Beispiel #24
0
		public void showCurso(int index)
		{
			//s_list = new ObservableCollection<MainViewModel.page_collection_wrapper> ();
			//vm._currentCurso=index;
			lo.currentCurso = index;
			player.Stop();
			_isHome = false;

			if (vm.CirclesList == null) {
				var myHandler = new Handler ();
				myHandler.Post(()=>{
					Toast.MakeText (this, "El curso se esta descargando", ToastLength.Short).Show();
				});
				return;
			}
			if (vm.CirclesList.Count <= index) {
				var myHandler = new Handler ();
				myHandler.Post(()=>{
					Toast.MakeText (this, "El curso se esta descargando", ToastLength.Short).Show();
				});
				return;
			}
			if (vm.CirclesList [index] == null) {
				var myHandler = new Handler ();
				myHandler.Post(()=>{
					Toast.MakeText (this, "El curso se esta descargando", ToastLength.Short).Show();
				});
				return;
			}


			switch (index) {
			case 0:
				lo._txtCursoN.Text = "Las rutas";
				break;
			case 1:
				lo._txtCursoN.Text = "Guía de Servicios";
				break;
			case 2:
				lo._txtCursoN.Text = "Guía de Identificación de Vida Silvestre";
				break;
			case 3:
				lo._txtCursoN.Text = "Las Cifras";
				break;

			default:
				lo._txtCursoN.Text = "";
				break;
			}

			//lo._txtCursoN.Text = "";
			lo._txtUnidadN.Text = "";
			_currentCurso = index;

			mDrawerLayout.CloseDrawer (mLeftDrawer);
			resetMLOs ();

			lo.getWorkSpaceLayout.SetBackgroundColor (Color.Transparent);
			lo.getWorkSpaceLayout.RemoveAllViews ();
			Console.WriteLine ("show_curso : INI");

			lo._spaceUnidades.RemoveAllViews ();
			lo._listLinearUnidades.Clear ();
			lo._listIconMap.Clear ();

			vm.SelectCircleCommand.Execute(vm.CirclesList[index]);
			PositionLO = index;


			//setIndex (lo._ListLOImages_S2 [0], new EventArgs ());
			/*
			MLearning.Core.ViewModels.MainViewModel.lo_by_circle_wrapper currentLearningObject = _CLO[0];
			vm.OpenLOSectionListCommand.Execute(currentLearningObject);
			*/

		}
 /// <summary>
 /// Updates the LVL information from the server.
 /// </summary>
 /// <param name="context">
 /// </param>
 private void UpdateLvl(DownloaderService context)
 {
     var h = new Handler(context.MainLooper);
     h.Post(new LvlRunnable(context, this.pPendingIntent));
 }
Beispiel #26
0
 public void Post(Action action)
 {
     // Post on main thread
     Handler handler = new Handler(Looper.MainLooper);
     handler.Post(action);
 }
Beispiel #27
0
		public override bool OnTouchEvent(MotionEvent e)
		{
			if (m_GestureDetector.OnTouchEvent(e))
			{
				m_PreviousMoveX = (int)e.GetX();
				m_PreviousMoveY = (int)e.GetY();
				return true;
			}



			var touchCount = e.PointerCount;

			if(touchCount == 3)
			{
				var myHandler = new Handler ();
				myHandler.Post(()=>{
					Toast.MakeText (m_Context, (int)e.GetX() +" " +(int)e.GetY(), ToastLength.Short).Show();
				});

			}

			switch (e.Action)
			{
			case MotionEventActions.Down:
			case MotionEventActions.Pointer1Down:
			case MotionEventActions.Pointer2Down:
				{
					if (touchCount >= 2)
					{
						var distance = this.Distance(e.GetX(0), e.GetX(1), e.GetY(0), e.GetY(1));
						m_PreviousDistance = distance;
						m_IsScaling = true;
					}
				}
				break;

			case MotionEventActions.Move:
				{
					if (touchCount >= 2 && m_IsScaling)
					{
						var distance = this.Distance(e.GetX(0), e.GetX(1), e.GetY(0), e.GetY(1));
						var scale = (distance - m_PreviousDistance) / this.DispDistance();
						m_PreviousDistance = distance;
						scale += 1;
						scale = scale * scale;
						this.ZoomTo(scale, m_Width / 2, m_Height / 2);
						this.Cutting();
					}
					else if (!m_IsScaling)
					{
						var distanceX = m_PreviousMoveX - (int)e.GetX();
						var distanceY = m_PreviousMoveY - (int)e.GetY();
						m_PreviousMoveX = (int)e.GetX();
						m_PreviousMoveY = (int)e.GetY();

						m_Matrix.PostTranslate(-distanceX, -distanceY);
						this.Cutting();
					}
				}
				break;
			case MotionEventActions.Up:
			case MotionEventActions.Pointer1Up:
			case MotionEventActions.Pointer2Up:
				{
					if (touchCount <= 1)
					{
						m_IsScaling = false;
					}
				}
				break;
			}
			return true;
		}
 public void btnCheckIn_OnClick(object sender, EventArgs eventArgs)
 {
     try
     {
         if (_currentLocation == null) {
             var myHandler = new Handler ();
             myHandler.Post (() => {
                 Toast.MakeText (this, "Determining Location, Wait One Moment and Try Again.", ToastLength.Long).Show ();
             });
             return;
         } else {
             if (groupID <= 2) {
                 string absResult = "You Are Not Within A Specified Zone.";
                 Button button = FindViewById<Button>(Resource.Id.btnCheckIn);
                 if (button.Text == "Check In") {
                     foreach (FacilityCoordinates fc in myFacilities) {
                         var fenceLat = fc.Latitude;
                         var fenceLon = fc.Longitude;
                         var R = 6371; // Radius of the earth in km
                         var dLat = deg2rad(_currentLocation.Latitude - fenceLat);  // deg2rad below
                         var dLon = deg2rad(_currentLocation.Longitude - fenceLon);
                         var a =
                             Math.Sin(dLat/2) * Math.Sin(dLat/2) +
                             Math.Cos(deg2rad(fenceLat)) * Math.Cos(deg2rad(_currentLocation.Latitude)) *
                             Math.Sin(dLon/2) * Math.Sin(dLon/2)
                             ;
                         var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1-a));
                         var d = R * c;
                         if (d <= 0.25) {
                             var locSvc = new ROMPLocation ();
                             string result = locSvc.CheckIn(sessionKey, fc.LocationID);
                             if (result == "Success"){
                                 absResult = "Check In Successful";
                                 button.Text = "Check Out";
                             } else {
                                 absResult = "An Unexpected Error Occurred. Try Again";
                             }
                         }
                     }
                 } else if (button.Text == "Check Out") {
                     var locSvc = new ROMPLocation ();
                     string result = locSvc.CheckOutWithoutLocation(sessionKey);
                     if (result == "Success"){
                         absResult = "Check Out Successful";
                         button.Text = "Check In";
                     } else {
                         absResult = "An Unexpected Error Occurred. Try Again";
                     }
                 }
                 var myHandler = new Handler ();
                 myHandler.Post (() => {
                     Toast.MakeText (this, absResult, ToastLength.Long).Show ();
                 });
             } else if (groupID > 2 && groupID <= 7) {
                 string absResult;
                 Button button = FindViewById<Button>(Resource.Id.btnCheckIn);
                 if (button.Text == "Check In") {
                     var locSvc = new ROMPLocation ();
                     string result = locSvc.CheckInWithLocation(sessionKey, -1, _currentLocation.Latitude, _currentLocation.Longitude);
                     if (result == "Success"){
                         absResult = "Check In Successful";
                         button.Text = "Check Out";
                     } else {
                         absResult = "An Unexpected Error Occurred. Try Again";
                     }
                     var myHandler = new Handler ();
                     myHandler.Post (() => {
                         Toast.MakeText (this, absResult, ToastLength.Long).Show ();
                     });
                 } else if (button.Text == "Check Out") {
                     var locSvc = new ROMPLocation ();
                     string result = locSvc.CheckOutWithoutLocation(sessionKey);
                     if (result == "Success"){
                         absResult = "Check Out Successful";
                         button.Text = "Check In";
                     } else {
                         absResult = "An Unexpected Error Occurred. Try Again";
                     }
                     var myHandler = new Handler ();
                     myHandler.Post (() => {
                         Toast.MakeText (this, absResult, ToastLength.Long).Show ();
                     });
                 }
             } else if (groupID == 8) {
                 var fenceLat = 48.46003187;
                 var fenceLon = -89.18908003;
                 var R = 6371; // Radius of the earth in km
                 var dLat = deg2rad(_currentLocation.Latitude - fenceLat);  // deg2rad below
                 var dLon = deg2rad(_currentLocation.Longitude - fenceLon);
                 var a =
                     Math.Sin(dLat/2) * Math.Sin(dLat/2) +
                     Math.Cos(deg2rad(fenceLat)) * Math.Cos(deg2rad(_currentLocation.Latitude)) *
                     Math.Sin(dLon/2) * Math.Sin(dLon/2)
                     ;
                 var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1-a));
                 var d = R * c;
                 //double distance = 60 * 1.1515 * Math.Acos(Math.Sin(Math.PI * _currentLocation.Latitude / 180) * Math.Sin(Math.PI * 48.46003187 / 180) + Math.Cos(Math.PI * _currentLocation.Latitude / 180) * Math.Cos(Math.PI * 48.46003187 / 180) * Math.Cos((_currentLocation.Longitude - -89.18908003) * Math.PI / 180)  * 180 / Math.PI );
                 var myHandler = new Handler ();
                 string absResult = d.ToString();
                 myHandler.Post (() => {
                     Toast.MakeText (this, absResult, ToastLength.Long).Show ();
                 });
             }
         }
     } catch (Exception e) {
         var myHandler = new Handler();
         myHandler.Post(() => {
             Android.Widget.Toast.MakeText(this, e.Message, Android.Widget.ToastLength.Long).Show();
         });
     }
 }
        private void IdentityProviderListRefreshCompleted(object sender, GetIdentityProviderListEventArgs e)
        {
            var handler = new Handler(Context.MainLooper); //We need to update on UI thread.
            handler.Post(() =>
            {
                if (null == e.Error)
                {
                    _identityProviderList = new ListView(Context)
                    {
                        LayoutParameters =
                            new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FillParent,
                                                        ViewGroup.LayoutParams.FillParent)
                    };
                    _identityProviderList.SetPadding(10, 0, 0, 0);
                    _identityProviderList.ItemClick += OnIdentityProviderListOnItemClick;
                    _identityProviderList.Divider = null;

                    AddView(_identityProviderList);

                    if (_identityProviderAdapter == null)
                        _identityProviderAdapter = new IdentityProviderAdapter(Context);
                
                    _identityProviderList.Adapter = _identityProviderAdapter;
                    _identityProviderAdapter.IdentityProviders = e.Result;

                    PostInvalidate();
                    HideProgressDialog();
                }
                else
                {
                    HideProgressDialog();
                    ShowAlertDialog("Oh no!", "An error occured with the message:\n" + e.Error.Message);
                }
            });
        }
 protected virtual void OnItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
 {
     using (var handler = new Handler(Looper.MainLooper))
     {
         handler.Post(() => NotifyDataSetChanged(e));
     }
 }
Beispiel #31
0
 protected override void OnCreate(Bundle bundle)
 {
     RequestWindowFeature(WindowFeatures.NoTitle);
     base.OnCreate (bundle);
     SetContentView (Resource.Layout.Main);
     mSharedPreferences = this.GetSharedPreferences ("CheckInPrefs", FileCreationMode.Private);
     string storedUser = mSharedPreferences.GetString ("StoredUser", "NONE");
     string storedPass = mSharedPreferences.GetString ("StoredPass", "NONE");
     if (!storedUser.Equals("NONE") || !storedPass.Equals("NONE")) {
         FindViewById<EditText>(Resource.Id.txtUsername).SetText(storedUser, TextView.BufferType.Normal);
         FindViewById<EditText>(Resource.Id.txtPassword).SetText(storedPass, TextView.BufferType.Normal);
         FindViewById<CheckBox>(Resource.Id.cbStoreUser).Checked = true;
     }
     FindViewById<CheckBox>(Resource.Id.cbStoreUser).CheckedChange += delegate {
         ISharedPreferencesEditor cbeditor = mSharedPreferences.Edit ();
         cbeditor.Remove("StoredUser");
         cbeditor.Remove("StoredPass");
         cbeditor.Commit();
     };
     Button button = FindViewById<Button> (Resource.Id.btnLogin);
     button.Click += delegate {
         TextView txtPassword = FindViewById<TextView> (Resource.Id.txtPassword);
         TextView txtUsername = FindViewById<TextView> (Resource.Id.txtUsername);
         if (string.IsNullOrEmpty(txtPassword.Text) || string.IsNullOrEmpty(txtUsername.Text)) {
             var myHandler = new Handler();
             myHandler.Post(() => {
                 Android.Widget.Toast.MakeText(this, "Please Provide a Username and Password.", Android.Widget.ToastLength.Long).Show();
             });
         } else {
             try {
                 var locSvc = new ROMPLocation();
                 var loginResp = new LoginResponse();
                 loginResp = locSvc.LearnerLogin(txtUsername.Text, txtPassword.Text);
                 if (loginResp.Success) {
                     CheckBox rememberMe = FindViewById<CheckBox> (Resource.Id.cbStoreUser);
                     ISharedPreferencesEditor editor = mSharedPreferences.Edit ();
                     if (rememberMe.Checked) {
                         editor.PutString("StoredUser", txtUsername.Text);
                         editor.PutString("StoredPass", txtPassword.Text);
                     } else {
                         editor.Remove("StoredUser");
                     }
                     editor.Commit();
                     if (loginResp.GroupID <= 2) {
                         var nextActivity = new Intent(this, typeof(ChooseModeActivity));
                         nextActivity.PutExtra("SessionKey", loginResp.SessionKey);
                         nextActivity.PutExtra("GroupID", loginResp.GroupID);
                         nextActivity.PutExtra("UserID", loginResp.UserID);
                         StartActivity(nextActivity);
                         Finish();
                     } else {
                         var nextActivity = new Intent(this, typeof(CheckInActivity));
                         nextActivity.PutExtra("SessionKey", loginResp.SessionKey);
                         nextActivity.PutExtra("GroupID", loginResp.GroupID);
                         nextActivity.PutExtra("UserID", loginResp.UserID);
                         StartActivity(nextActivity);
                         Finish();
                     }
                 } else {
                     var myHandler = new Handler();
                     myHandler.Post(() => {
                         Android.Widget.Toast.MakeText(this, "Login Failed. Please Try Again.", Android.Widget.ToastLength.Long).Show();
                     });
                 }
             } catch (Exception e) {
                 var myHandler = new Handler();
                 myHandler.Post(() => {
                     Android.Widget.Toast.MakeText(this, e.Message, Android.Widget.ToastLength.Long).Show();
                 });
                 System.Diagnostics.Debug.Write(e.Message);
             }
         }
     };
 }
Beispiel #32
0
        private void Reproducir(Cancion cancion)
        {
            Action action = new Action(DesactivarControles);

            Handler.Post(action);
            byte[]            archivo       = null;
            bool              huboExcepcion = false;
            APIGatewayService api           = new APIGatewayService();

            if (!UtileriasDeArchivos.CancionYaDescargada(cancion.IdArchivo))
            {
                try
                {
                    archivo = api.DescargarArchivoPorId(cancion.IdArchivo);
                    cancion.CargarMetadatosDeLaCancion(Usuario.Id);
                }
                catch (System.Exception)
                {
                    Toast.MakeText(View.Context, "Error al realizar la descarga, intente de nuevo mas tarde", ToastLength.Long).Show();
                    huboExcepcion = true;
                }
            }
            else
            {
                try
                {
                    archivo = UtileriasDeArchivos.LeerArchivoPorId(cancion.IdArchivo);
                }
                catch (ArgumentException)
                {
                    huboExcepcion = true;
                }
            }

            if (!huboExcepcion && archivo != null && archivo.Length > 0)
            {
                if (Canciones[IndiceActual].Metadatos == null)
                {
                    bool resultado = false;
                    try
                    {
                        resultado = api.CrearNuevoMetadato(Usuario.Id, Canciones[IndiceActual].Id);
                    }
                    catch (Exception)
                    {
                        Toast.MakeText(View.Context, "No se pudo registrar el MeGusta", ToastLength.Long).Show();
                    }

                    if (!resultado)
                    {
                        Toast.MakeText(View.Context, "No se pudo registrar el MeGusta", ToastLength.Long).Show();
                    }
                    else
                    {
                        Canciones[IndiceActual].CargarMetadatosDeLaCancion(Usuario.Id);
                    }
                }
                var buttonLike = View.FindViewById <ImageButton>(Resource.Id.ibtnLike);
                if (cancion.Metadatos.MeGusta)
                {
                    buttonLike.SetImageDrawable(View.Context.GetDrawable(Resource.Drawable.ic_ss_like));
                }
                else
                {
                    buttonLike.SetImageDrawable(View.Context.GetDrawable(Resource.Drawable.ic_ss_dislike));
                }
                var buttonReproducir = View.FindViewById <ImageButton>(Resource.Id.ibtnReproducir);
                buttonReproducir.SetImageDrawable(View.Context.GetDrawable(Resource.Drawable.ic_ss_pausa));
                var txtCancion = View.FindViewById <TextView>(Resource.Id.txtNombreCancion);
                txtCancion.Text = cancion.Nombre;
                var txtArtista = View.FindViewById <TextView>(Resource.Id.txtNombreArtista);
                if (cancion.Artistas.FirstOrDefault() != null)
                {
                    txtArtista.Text = cancion.Artistas.FirstOrDefault().Nombre;
                }
                var      txtTiempoTotal = View.FindViewById <TextView>(Resource.Id.txtDuracionTotal);
                TimeSpan tiempoActual   = TimeSpan.FromMilliseconds(Reproductor.Duration);
                txtTiempoTotal.Text = System.String.Format("{0}:{1:D2}", tiempoActual.Minutes, tiempoActual.Seconds);
                try
                {
                    Reproductor.Reset();
                    Java.IO.File archivoTemporal = Java.IO.File.CreateTempFile(cancion.Id, "mp3", Context.CacheDir);
                    archivoTemporal.DeleteOnExit();
                    Java.IO.FileOutputStream outputStream = new Java.IO.FileOutputStream(archivoTemporal);
                    outputStream.Write(archivo);
                    outputStream.Close();
                    Java.IO.FileInputStream fis = new Java.IO.FileInputStream(archivoTemporal);
                    Reproductor.SetDataSource(fis.FD);
                    Reproductor.Prepare();
                    Reproductor.Start();
                    CancionCorriendo = true;
                }
                catch (System.Exception e)
                {
                    Toast.MakeText(View.Context, e.Message, ToastLength.Long).Show();
                }

                AgregarCancionAHistorial(cancion.Id);
            }
            action = new Action(ActivarControles);
            Handler.Post(action);
            ActualizadorCorriendo = true;
        }
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
        {
            View rootView = inflater.Inflate(Resource.Layout.user_detail, container, false);

            if (_user != null) {
                ((TextView)rootView.FindViewById (Resource.Id.user_name)).Text = $"{_user.FirstName} {_user.LastName}";
                ((TextView)rootView.FindViewById (Resource.Id.mail_header)).Text = $"[Email]";
                ((TextView)rootView.FindViewById (Resource.Id.user_mail)).Text = _user.Email;
                ((TextView)rootView.FindViewById (Resource.Id.phone_header)).Text = $"[Telefon]";
                ((TextView)rootView.FindViewById (Resource.Id.user_phone)).Text = _user.Phone;
                ((TextView)rootView.FindViewById (Resource.Id.cell_header)).Text = $"[Mobil]";
                ((TextView)rootView.FindViewById (Resource.Id.user_cell)).Text = _user.Cell;

                var imageView = (ImageView)rootView.FindViewById (Resource.Id.user_image);

                Handler handler = new Handler (Context.MainLooper);
                Task.Run (() => {
                    var imageBitmap = ((ImageService)ServiceLocator.Current.GetInstance<ImageService>()).GetUserPicture(_user);
                    Runnable runnable = new Runnable (() => {
                        imageView.SetImageBitmap (imageBitmap);
                    });
                    handler.Post (runnable);
                });
            }
            return rootView;
        }
        //
        // Marker related listeners.
        //
        public bool OnMarkerClick(Marker marker)
        {
            // This causes the marker at Perth to bounce into position when it is clicked.
            if (marker.Equals(mPerth)) {
                Handler handler = new Handler ();
                long start = SystemClock.UptimeMillis ();
                Projection proj = mMap.Projection;
                Point startPoint = proj.ToScreenLocation(PERTH);
                startPoint.Offset(0, -100);
                LatLng startLatLng = proj.FromScreenLocation(startPoint);
                long duration = 1500;

                IInterpolator interpolator = new BounceInterpolator();

                Runnable run = null;
                run = new Runnable (delegate {
                        long elapsed = SystemClock.UptimeMillis () - start;
                        float t = interpolator.GetInterpolation ((float) elapsed / duration);
                        double lng = t * PERTH.Longitude + (1 - t) * startLatLng.Longitude;
                        double lat = t * PERTH.Latitude + (1 - t) * startLatLng.Latitude;
                        marker.Position = (new LatLng(lat, lng));

                        if (t < 1.0) {
                            // Post again 16ms later.
                            handler.PostDelayed(run, 16);
                        }
                });
                handler.Post(run);
            }
            // We return false to indicate that we have not consumed the event and that we wish
            // for the default behavior to occur (which is for the camera to move such that the
            // marker is centered and for the marker's info window to open, if it has one).
            return false;
        }
Beispiel #35
0
        private void StartDownloadWatcher()
        {
            if (_downloadWatcherHandler != null)
            {
                return;
            }

            // Create an instance for a runnable-handler
            _downloadWatcherHandler = new Android.OS.Handler();

            // Create a runnable, restarting itself to update every file in the queue
            _downloadWatcherHandlerRunnable = new Java.Lang.Runnable(() => {
                var queueDownload = Queue.Cast <DownloadFileImplementation>();
                var file          = queueDownload.FirstOrDefault();
                if (file != null)
                {
                    if (file.Status == DownloadFileStatus.PAUSED)
                    {
                        var fileTemp = queueDownload.FirstOrDefault(x => x.Status != DownloadFileStatus.PAUSED);
                        if (fileTemp != null)
                        {
                            file = fileTemp;
                        }
                    }

                    if (file.Status == DownloadFileStatus.INITIALIZED)
                    {
                        string destinationPathName = null;
                        if (PathNameForDownloadedFile != null)
                        {
                            destinationPathName = PathNameForDownloadedFile(file);
                        }
                        file.StartDownload(_downloadManager, destinationPathName, true, NotificationVisibility, IsVisibleInDownloadsUi);
                    }

                    var query = new Android.App.DownloadManager.Query();
                    query.SetFilterById(file.Id);
                    try
                    {
                        using (var cursor = _downloadManager.InvokeQuery(query))
                        {
                            if (cursor != null && cursor.MoveToNext())
                            {
                                UpdateFileProperties(cursor, file);
                            }
                            else
                            {
                                // This file is not listed in the native download manager anymore. Let's mark it as canceled.
                                Abort(file);
                            }
                            cursor?.Close();
                        }
                    }
                    catch (Android.Database.Sqlite.SQLiteException)
                    {
                        // I lately got an exception that the database was unaccessible ...
                    }
                }
                _downloadWatcherHandler?.PostDelayed(_downloadWatcherHandlerRunnable, 1000);
            });
            // Start this playing handler immediately
            _downloadWatcherHandler.Post(_downloadWatcherHandlerRunnable);
        }