예제 #1
1
		public FriendAdapter(Activity context, FriendsViewModel viewModel)
		{
			this.context = context;
			this.viewModel = viewModel;
			viewModel.Friends.CollectionChanged += (sender, e) => context.RunOnUiThread (NotifyDataSetChanged);

		}
예제 #2
0
파일: Call.cs 프로젝트: dsb92/patientcare
	    public static void MakeCall(CallEntity callEntity, Activity activity)
	    {
            var category = callEntity.Category;
            var choice = callEntity.Choice ?? "";
            var detail = callEntity.Detail ?? "";

	        new AlertDialog.Builder(activity)
	            .SetTitle(category + " " + choice + " " + detail)
	            .SetMessage(Strings.CallSendMessage)
	            .SetPositiveButton(Strings.CallSend, delegate
	            {
                    ThreadPool.QueueUserWorkItem(o =>
                    {
                        activity.RunOnUiThread(() =>
                        {
                            dialog = new ProgressDialog(activity);
                            dialog.SetMessage(Strings.SpinnerDataSending);
                            dialog.SetCancelable(false);
                            dialog.Show();
                        });

                        try
                        {
                            ICall patientCall = new PatientCall();
                            // Assign the callid with the returned MongoDB id
                            callEntity._id = patientCall.MakeCall(callEntity);

                            activity.RunOnUiThread(() =>
                            {
                                // Call successfull, take the user to myCalls
                                activity.ActionBar.SelectTab(activity.ActionBar.GetTabAt(1));
                                SetNewCalls(callEntity);
                                dialog.Hide();
                            });
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("ERROR making call: " + ex.Message);

                            activity.RunOnUiThread(() =>
                            {
                                dialog.Hide();

                                new AlertDialog.Builder(activity).SetTitle(Strings.Error)
                                    .SetMessage(Strings.ErrorSendingCall)
                                    .SetPositiveButton(Strings.OK,
                                        delegate { }).Show();
                            });
                        }
              
                    });
             
	            })
            .SetNegativeButton(Strings.Cancel, delegate {/* Do nothing */ })
            .Show();
	    }
		public void start(ProcessButton button,Activity activity) {
 
			activity.RunOnUiThread (() => {
				action = ()=> UpdateProgress(button,0);
				messageHandler.PostDelayed(action,generateDelay());
			}); 
		}
예제 #4
0
        public static void Alert(Activity context, string title, string message, bool CancelButton, Action<Result> callback = null)
        {
            context.RunOnUiThread(() =>
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.SetTitle(title);
                builder.SetMessage(message);

                if (callback != null)
                {
                    builder.SetPositiveButton("Ok", (sender, e) =>
                    {
                        callback(Result.Ok);
                    });

                    if (CancelButton)
                    {
                        builder.SetNegativeButton("Cancel", (sender, e) =>
                        {
                            callback(Result.Canceled);
                        });
                    }
                }
                else
                {
                    builder.SetPositiveButton("OK", (sender, e) => { });
                }

                builder.Show();
            });
        }
예제 #5
0
        public void SetIcon(Item item, ImageView view, Activity activity)
        {
            var path = GetIconPath(item);
            if (File.Exists(path))
            {
                var icon = BitmapFactory.DecodeFile(path);

                if (view != null & activity != null)
                {
                    activity.RunOnUiThread(
                        () => view.SetImageBitmap(BitmapFactory.DecodeFile(path)));
                }
            }
            _iconsToLoad.Enqueue
                (
                    new IconToLoad
                    {
                        Item = item,
                        ImageView = view,
                        Activity = activity
                    }
                );

            lock (_backgroundWorker)
            {
                if (!_backgroundWorker.IsBusy)
                {
                    _backgroundWorker.RunWorkerAsync();
                }
            }
        }
예제 #6
0
        private ProtoPadServer(View window, int? overrideListeningPort = null, string overrideBroadcastedAppName = null)
        {
            _window = window;
            _contextActivity = window.Context as Activity;

            _httpServer = new SimpleHttpServer(responseBytes =>
            {
                var response = "{}";
                var remoteCommandDoneEvent = new AutoResetEvent(false);
                _contextActivity.RunOnUiThread(() => Response(responseBytes, remoteCommandDoneEvent, ref response));
                remoteCommandDoneEvent.WaitOne();
                return response;
            });

            IPAddress broadCastAddress;
            using (var wifi = _contextActivity.GetSystemService(Android.Content.Context.WifiService) as WifiManager)
            {
                _mcLock = wifi.CreateMulticastLock("ProtoPadLock");
                _mcLock.Acquire();
                broadCastAddress = GetBroadcastAddress(wifi);
            }

            BroadcastedAppName = overrideBroadcastedAppName ?? String.Format("ProtoPad Service on ANDROID Device {0}", Android.OS.Build.Model);
            ListeningPort = overrideListeningPort ?? 8080;
            LocalIPAddress = Helpers.GetCurrentIPAddress();

            _udpServer = new UdpDiscoveryServer(BroadcastedAppName, String.Format("http://{0}:{1}/", LocalIPAddress, ListeningPort), broadCastAddress);
        }
		public ConverstationAdapter(Activity context, ConversationsViewModel viewModel)
		{
			this.context = context;
			this.viewModel = viewModel;
			viewModel.Conversations.CollectionChanged += (sender, e) => context.RunOnUiThread (NotifyDataSetChanged);

		}
예제 #8
0
		public AvatarAdapter(Activity context, ProfileViewModel viewModel)
		{
			this.context = context;
			this.viewModel = viewModel;
			viewModel.Avatars.CollectionChanged += (sender, e) => context.RunOnUiThread (NotifyDataSetChanged);

		}
예제 #9
0
		public ButtonItem (Activity oActivity, Game oGame)
		{
			this.oActivity = oActivity;
			this.oGame = oGame;
			oImageButton = oActivity.FindViewById<ImageButton> (Int32.Parse( Game.buttons[nahodnik.Next(0,Game.buttons.Length-1)].ToString()));
			seznamVisibleButtons.Add (this);

			oActivity.RunOnUiThread (() => oImageButton.Visibility = ViewStates.Visible);
			oActivity.RunOnUiThread (() => oImageButton.Enabled = true);

			if (OptionsHodnoty.TouchMode) 
			{
				//oImageButton.Touch += HandleClick;
				//oImageButton.SetOnTouchListener (this);
			} else {
				oImageButton.Click += HandleClick;
			}
		}
예제 #10
0
		public void ShowEmptyHistory(Activity activity)
		{
			activity.RunOnUiThread(() =>
			{
				var item = new DataObject(string.Empty);
				var items = new List<DataObject> { item };
				Items = items;
			});
			
		}
예제 #11
0
 public static void CloseDialog(Activity currentActivity)
 {
     currentActivity.RunOnUiThread(() =>
     {
         if (_currentDialog != null && _currentDialog.IsShowing)
         {
             _currentDialog.Dismiss();
         }
     });
 }
 /// <summary>
 /// Initialize the binding manager for an activity.
 /// </summary>
 /// <param name="bindings">The binding manager for the activity.</param>
 /// <param name="activity">The activity that owns the binding manager.</param>
 public static void Initialize(this BindingManager bindings, Activity activity)
 {
     UpdateScheduler.Initialize(action =>
     {
         ThreadPool.QueueUserWorkItem(delegate(Object obj)
         {
             activity.RunOnUiThread(action);
         });
     });
 }
예제 #13
0
		public static void MakeErrorPopUp(Activity activity, ErrorType error)
		{
			if (activity == null) throw new ArgumentNullException("activity");

			activity.RunOnUiThread(() =>
			{
				_errorDialog = new AlertDialog.Builder(activity)
					.SetPositiveButton(Resource.String.TryAgainButtonText, OnTryAgainButtonClicked)
					.SetTitle(ResolveErrorTitle(error))
					.SetMessage(ResolveErrorMessage(error))
					.Create();
				_errorDialog.Show();
			});
		}
예제 #14
0
        private ProtoPadServer(Activity activity, int? overrideListeningPort = null, string overrideBroadcastedAppName = null)
        {
            _contextActivity = activity;

            BroadcastedAppName = overrideBroadcastedAppName ?? String.Format("ProtoPad Service on ANDROID Device {0}", Android.OS.Build.Model);
            ListeningPort = overrideListeningPort ?? 8080;
            LocalIPAddress = Helpers.GetCurrentIPAddress();

            var mainMonodroidAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name.ToLower() == "mono.android");

            var requestHandlers = new Dictionary<string, Func<byte[], string>>
                {
                    {"GetMainXamarinAssembly", data => mainMonodroidAssembly.FullName},
                    {"WhoAreYou", data => "Android"},
                    {"ExecuteAssembly", data =>
                        {
                            var response = "{}";
                            var remoteCommandDoneEvent = new AutoResetEvent(false);
                            _contextActivity.RunOnUiThread(() => Response(data, remoteCommandDoneEvent, ref response));
                            remoteCommandDoneEvent.WaitOne();
                            return response;
                        }
                    }
                };

            _httpServer = new SimpleHttpServer(ListeningPort, requestHandlers);

            IPAddress broadCastAddress;
            using (var wifi = _contextActivity.GetSystemService(Android.Content.Context.WifiService) as WifiManager)
            {
                try
                {
                    _mcLock = wifi.CreateMulticastLock("ProtoPadLock");
                    _mcLock.Acquire();

                }
                catch (Java.Lang.SecurityException e)
                {
                    Debug.WriteLine("Could not optain Multicast lock: {0}. Did you enable CHANGE_WIFI_MULTICAST_STATE permission in your app manifest?", e.Message);
                }

                broadCastAddress = GetBroadcastAddress(wifi);
            }

            var inEmulator = Build.Brand.Equals("generic", StringComparison.InvariantCultureIgnoreCase);
            _udpServer = new UdpDiscoveryServer(BroadcastedAppName, String.Format("http://{0}:{1}/", inEmulator ? "localhost" : LocalIPAddress.ToString(), inEmulator ? "?" : ListeningPort.ToString()), broadCastAddress);
        }
        /// <summary>
        /// Refreshed the ad for the view
        /// </summary>
        /// <param name="view"></param>
        public static void LoadAd(Activity activity, View view)
        {
            if (String.IsNullOrEmpty (activity.GetText(Resource.String.AdPublisherID)))
            {
                view.Visibility = ViewStates.Gone;
                return;
            }

            Logging.Log (null, Logging.LoggingTypeDebug, "LoadAd()");

            Task.Factory.StartNew (() => {
                activity.RunOnUiThread(() => {
                    view.Visibility = ViewStates.Visible;

                    IntPtr methodId = JNIEnv.GetStaticMethodID (_helperClass, "loadAd", "(Landroid/view/View;)V");
                    JNIEnv.CallStaticVoidMethod (_helperClass, methodId, new JValue (view));
                });
            });
        }
예제 #16
0
        public static Task <T> WaitOnUiThread <T>(this Android.App.Activity act, Func <T> f)
        {
            TaskCompletionSource <T> tcs = new TaskCompletionSource <T>();

            act.RunOnUiThread(() =>
            {
                T result = default(T);
                try
                {
                    result = f();
                }
                catch (Exception e)
                {
                    // Ignore it. But it should be impossible for now
                }
                tcs.SetResult(result);
            });
            return(tcs.Task);
        }
예제 #17
0
		public void ShowCountdownViews(Activity activity, bool isHelpRequired)
		{
			ShowAnalyzerViews(activity);
			activity.RunOnUiThread(() =>
			{
				_countdownText.Visibility = ViewStates.Visible;
			});
			StopAnimation(activity);
		}
예제 #18
0
		public static void getAllOpenTournaments(Activity a, Action<List<TournamentModel>> succes, Action<int, String> error) 
		{
			new Thread(new ThreadStart(() =>
			{
				try
				{
					HttpWebRequest request = createWebRequest("tournament.php", "action=getAllOpenTournaments");
					string responseBody = null;
					using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)  
					{    
						var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
						responseBody = reader.ReadToEnd();
						List<TournamentModel> tournaments = JsonConvert.DeserializeObject<List<TournamentModel>>(responseBody);
						a.RunOnUiThread(() => succes(tournaments));
					}
				}
				catch (WebException we )
				{
					// Something when wrong with the connection
					Console.WriteLine( we.Message );
					a.RunOnUiThread(() => error(-1, we.Message));
				}
				catch(JsonSerializationException e)
				{
					// Could not turn JSON into objects
					a.RunOnUiThread(() => error(-2, e.Message));
				}
			}
			)).Start();
		}
예제 #19
0
		public void StopAnimation(Activity activity)
		{
			activity.RunOnUiThread(() => _animationView.ClearAnimation());
		}
예제 #20
0
		public void StartAnimation(Activity activity)
		{
			activity.RunOnUiThread(() =>
			{
				var animation = AnimationUtils.LoadAnimation(Activity, Resource.Animation.ShakeAnimation);
				_animationView.StartAnimation(animation);
				_animationView.Visibility = ViewStates.Visible;
			});
		}
예제 #21
0
		public void UpdateCountdownView(Activity activity, AudioRecorderEventArgs e)
		{
			activity.RunOnUiThread(() =>
			{
				if (e.IsCounting)
				{
					_countdownText.Text = e.Counter.ToString(CultureInfo.InvariantCulture);
				}
			});
		}
예제 #22
0
		private void ChangeResultText(Activity activity, string msg)
		{
			activity.RunOnUiThread(() => { if (_resultText != null) _resultText.Text = msg; });
		}
예제 #23
0
		public static void addContestant(Activity a, int tournamentId, int userId, Action succes) 
		{
			new Thread(new ThreadStart(() =>
			                           {
				try
				{
					HttpWebRequest request = createWebRequest("tournament.php", "action=addContestant&tournamentId="+tournamentId+"&userId="+userId);
					string responseBody = null;
					using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)  
					{    
						var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
						responseBody = reader.ReadToEnd();
						JObject json = JObject.Parse(responseBody);
						int status = (int)json["status"];
						String message = (string)json["message"];
						if(status == 0)
						{
							a.RunOnUiThread(() => succes());
						}
						else
						{
							throw new ServerDataException(message);
						}
					}
				}
				catch (Exception e )
				{
					throw e;
				}
			}
			)).Start();
		}
예제 #24
0
		public void EnableStartButton(Activity activity, bool flag)
		{
			EnableStartButtonFlag = flag;
			if (_startButton != null)
			{
				activity.RunOnUiThread(() => _startButton.Enabled = EnableStartButtonFlag);
				
			}
		}
예제 #25
0
		public void ShowStartViews(Activity activity, bool isHelpRequired)
		{
			AnalyzerFailed = false;
			HideAllViews(activity);

			activity.RunOnUiThread(() =>
			{
				_startButton.Visibility = ViewStates.Visible;
				_animationView.Visibility = ViewStates.Visible;
				_smartPhoneView.Visibility = ViewStates.Visible;
				_startButton.Enabled = EnableStartButtonFlag;
				_progressBar.Progress = 0;

				if (isHelpRequired)
				{
					_manualText.Text = Resources.GetText(Resource.String.Slide1_Text1);
					_manualText.Visibility = ViewStates.Visible;
					_manualText2.Visibility = ViewStates.Visible;
				}
			});
			StopAnimation(activity);
		}
예제 #26
0
		public void ShowAnalyzerViews(Activity activity)
		{
			HideAllViews(activity);

			activity.RunOnUiThread(() =>
			{
				_progressBar.Visibility = ViewStates.Visible;
				_statusText.Visibility = ViewStates.Visible;
				_animationView.Visibility = ViewStates.Visible;
				_smartPhoneView.Visibility = ViewStates.Visible;
			});
		}
예제 #27
0
        internal void LaunchApp(Activity ctx, ParseUser withUser, Action uiCallback)
        {
            // Fetch the person corresponding to the user
            Task.Factory.StartNew (() => {
                var query = new ParseQuery ("Person");
                query.SetCachePolicy (ParseQuery.CachePolicy.CacheElseNetwork);
                query.WhereEqualTo ("parseUser", withUser);
                query.Include ("parseUser");
                ParseObject self = null;
                try {
                    self = query.First;
                } catch (ParseException ex) {
                    // We may have a stall result from a previous registration
                    if (query.HasCachedResult) {
                        query.ClearCachedResult ();
                        try {
                            self = query.First;
                        } catch {
                            Android.Util.Log.Error ("Landing", "Error when trying to retrieve user 2. Normal if empty. {0}", ex.ToString ());
                        }
                    }
                    Android.Util.Log.Error ("Landing", "Error when trying to retrieve user. Normal if empty. {0}", ex.ToString ());
                }
                // First time ever, fill the info
                if (self == null) {
                    TabPerson person = null;
                    // Check if our TabPerson wasn't created indirectly by another user
                    query = new ParseQuery ("Person");
                    query.WhereEqualTo ("emails", TabPerson.MD5Hash (withUser.Email));
                    try {
                        person = TabPerson.FromParse (query.First);
                        person.AssociatedUser = withUser;
                    } catch {
                        // We use the main address email we got by parseUser
                        // and we will fill the rest lazily later from profile
                        // idem for the display name
                        person = new TabPerson {
                            AssociatedUser = withUser,
                            Emails = new string[] { withUser.Email }
                        };
                    }
                    return person;
                } else {
                    TabPerson.CurrentPerson = TabPerson.FromParse (self);
                    return null;
                }
            }).ContinueWith (t => {
                ctx.RunOnUiThread (() => {
                    // If the user was created, we setup a CursorLoader to query the information we need
                    if (t.Result != null) {
                        var person = t.Result;
                        person.DisplayName = profile.DisplayName;
                        person.Emails = profile.Emails.Union (person.Emails);
                        person.ToParse ().SaveEventually ();
                        TabPerson.CurrentPerson = person;
                    }

                    if (uiCallback != null)
                        uiCallback ();
                    ctx.Finish ();
                    ctx.StartActivity (typeof (MainActivity));
                });
            });
        }
예제 #28
0
		public void ShowResultViews(Activity activity, string result, bool isHelpRequired)
		{
			if (Activity == null) return;

			AnalyzerSuccessful = true;

			HideAllViews(activity);
			ChangeStatusText(activity, Resources.GetString(Resource.String.AnalysisSuccessful));
			ChangeResultText(activity, result);
			StopAnimation(activity);

			activity.RunOnUiThread(() =>
			{
				ChangeSeekBarColor(_progressBar);
				_cancelButton.Visibility = ViewStates.Visible;
				_feedbackButton.Visibility = ViewStates.Visible; //TODO: Build other feedback button behavior when FAILED status.
				_progressBar.Visibility = ViewStates.Visible;
				_resultViews.Visibility = ViewStates.Visible;
				ProgressBarToMax();

				if (isHelpRequired)
				{
					_dontShowAgainBox.Visibility = ViewStates.Visible;
					_manualText.Text = Resources.GetText(Resource.String.Slide3_Text2);
					_manualText.Visibility = ViewStates.Visible;
				}
			});

			ShowsResults = true;
		}
예제 #29
0
        private void ReformatAndSearchKennzeichen(Bitmap bitmap, string timestamp)
        {
            var canvas = new Canvas(bitmap);
            var tPaint = new Paint {
                TextSize = 35, Color = Color.Red
            };

            tPaint.SetStyle(Paint.Style.Fill);
            tPaint.AntiAlias = true;
            var bPaint = new Paint();

            byte[] imageContent;
            using (var output = new System.IO.MemoryStream())
            {
                canvas.DrawBitmap(bitmap, 0f, 0f, bPaint);

                var width = tPaint.MeasureText(timestamp);
                canvas.DrawText(timestamp, bitmap.Width - width - 25f, bitmap.Height - 25f, tPaint);

                bitmap.Compress(Bitmap.CompressFormat.Jpeg, 50, output);
                imageContent = output.ToArray();

                output.Flush();
                output.Close();
                output.Dispose();

                bitmap.Recycle();
                bitmap.Dispose();
                bitmap = null;
            }

            canvas.Dispose();
            canvas = null;

            bPaint.Dispose();
            bPaint = null;

            tPaint.Dispose();
            tPaint = null;

            var progressDialog = ProgressDialog.Show(MainActivity.Instance, "Bitte warten...", "Die Kennzeichen werden gesucht...", true);

            new System.Threading.Thread(new System.Threading.ThreadStart(delegate
            {
                //save image
                var dataFolder = System.IO.Path.Combine(MainActivity.Instance.ApplicationInfo.DataDir, "kennzeichen_data");
                if (!System.IO.Directory.Exists(dataFolder))
                {
                    System.IO.Directory.CreateDirectory(dataFolder);
                }

                var imagePath = System.IO.Path.Combine(dataFolder, $"temp_{ Guid.NewGuid()}.jpg");
                System.IO.File.WriteAllBytes(imagePath, imageContent);

                // get kennzeichen when foto saved
                var result = App.KennzeichenRecognizer.Recognize(imagePath, "eu");

                // delete tempfoto
                System.IO.File.Delete(imagePath);

                //HIDE PROGRESS DIALOG
                _activity.RunOnUiThread(() =>
                {
                    progressDialog.Hide();

                    // invoke event on kennzeichenfound
                    ((SmartCameraPage)Element).RaiseLicenseFoundEvent(result);

                    // go back
                    Element.Navigation.PopModalAsync();
                });
            })).Start();
        }
예제 #30
0
		private void HideAllViews(Activity activity)
		{
			activity.RunOnUiThread(() =>
			{
				InitializeUi(activity);
				_cancelButton.Visibility = ViewStates.Invisible;
				_feedbackButton.Visibility = ViewStates.Invisible;
				_progressBar.Visibility = ViewStates.Invisible;
				_statusText.Visibility = ViewStates.Invisible;
				_manualText.Visibility = ViewStates.Invisible;
				_manualText2.Visibility = ViewStates.Invisible;
				_startButton.Visibility = ViewStates.Invisible;
				_resultViews.Visibility = ViewStates.Invisible;
				_countdownText.Visibility = ViewStates.Invisible;
				_animationView.Visibility = ViewStates.Invisible;
				_smartPhoneView.Visibility = ViewStates.Invisible;
				_dontShowAgainBox.Visibility = ViewStates.Invisible;
			});

			ShowsResults = false;
		}
예제 #31
0
 public static void ShowDialog(string message, Activity currentActivity)
 {
     currentActivity.RunOnUiThread(() => LocalShowDialog(message, currentActivity));
 }
예제 #32
0
		public void ChangeStatusText(Activity activity, string msg)
		{
			activity.RunOnUiThread(() => { if (_statusText != null) _statusText.Text = msg; });
		}