コード例 #1
0
        async Task GetSendSMSPermissionAsync()
        {
            //Check to see if any permission in our group is available, if one, then all are
            const string permission = Manifest.Permission.SendSms;
            if (CheckSelfPermission(Manifest.Permission.SendSms) == (int)Permission.Granted)
            {
                await SMSSend();
                return;
            }

            //need to request permission
            if (ShouldShowRequestPermissionRationale(permission))
            {
               
                var callDialog = new AlertDialog.Builder(this);
                callDialog.SetTitle("explain");
                callDialog.SetMessage("This app needt to send sms so it need sms send permission");
                callDialog.SetNeutralButton("yes", delegate {
                   RequestPermissions(PermissionsLocation, RequestLocationId);
                });
                callDialog.SetNegativeButton("no", delegate { });
               
                callDialog.Show();
                return;
            }
            //Finally request permissions with the list of permissions and Id
            RequestPermissions(PermissionsLocation, RequestLocationId);
        }
コード例 #2
0
        /// <summary>
        /// Shows the message box.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="caption">The caption.</param>
        /// <param name="button">The button.</param>
        /// <param name="icon">The icon.</param>
        /// <returns>The message result.</returns>
        /// <exception cref="ArgumentException">The <paramref name="message"/> is <c>null</c> or whitespace.</exception>
        protected virtual Task<MessageResult> ShowMessageBox(string message, string caption = "", MessageButton button = MessageButton.OK, MessageImage icon = MessageImage.None)
        {
            var messageResult = MessageResult.Cancel;
            var context = Catel.Android.ContextHelper.CurrentContext;
            var builder = new AlertDialog.Builder(context);

            switch (button)
            {
                case MessageButton.OK:
                    builder.SetPositiveButton("OK", (sender, e) => { messageResult = MessageResult.OK; });
                    break;

                case MessageButton.OKCancel:
                    builder.SetPositiveButton("OK", (sender, e) => { messageResult = MessageResult.OK; });
                    builder.SetCancelable(true);
                    break;

                case MessageButton.YesNo:
                    builder.SetPositiveButton("Yes", (sender, e) => { messageResult = MessageResult.Yes; });
                    builder.SetNegativeButton("No", (sender, e) => { messageResult = MessageResult.No; });
                    break;

                case MessageButton.YesNoCancel:
                    builder.SetPositiveButton("Yes", (sender, e) => { messageResult = MessageResult.Yes; });
                    builder.SetNegativeButton("No", (sender, e) => { messageResult = MessageResult.No; });
                    builder.SetCancelable(true);
                    break;

                default:
                    throw new ArgumentOutOfRangeException("button");
            }

            return Task<MessageResult>.Run(() =>
            {
                builder.SetMessage(message).SetTitle(caption);
                builder.Show();

                return messageResult;
            });
        }
コード例 #3
0
ファイル: ActMemberAdd.cs プロジェクト: eduo03/Census
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.LayNameAdd);


            txtfname      = FindViewById <EditText> (Resource.Id.txtfname);
            txtmname      = FindViewById <EditText> (Resource.Id.txtmname);
            txtlname      = FindViewById <EditText> (Resource.Id.txtlname);
            txtexname     = FindViewById <EditText> (Resource.Id.txtexname);
            txtbday       = FindViewById <EditText> (Resource.Id.txtbday);
            txtreligion   = FindViewById <EditText> (Resource.Id.txtreligion);
            txtoccupation = FindViewById <EditText> (Resource.Id.txtoccupation);

            spngender           = FindViewById <Spinner> (Resource.Id.spngender);
            spnrhouse           = FindViewById <Spinner> (Resource.Id.spnrhouse);
            spnbirthcert        = FindViewById <Spinner> (Resource.Id.spnbirthcert);
            spnmarital          = FindViewById <Spinner> (Resource.Id.spnmarital);
            spnschoolattendance = FindViewById <Spinner> (Resource.Id.spnschoolattendance);
            spnschoolhigh       = FindViewById <Spinner> (Resource.Id.spnschoolhigh);
            spnliteracy         = FindViewById <Spinner> (Resource.Id.spnliteracy);
            spnworkstatus       = FindViewById <Spinner> (Resource.Id.spnworkstatus);

            var adaptergender = ArrayAdapter.CreateFromResource(
                this, Resource.Array.Gender_Spinner, Android.Resource.Layout.SimpleSpinnerItem);

            adaptergender.SetDropDownViewResource(Android.Resource.Layout.SimpleListItemActivated1);
            spngender.Adapter = adaptergender;

            var adapterhouse = ArrayAdapter.CreateFromResource(
                this, Resource.Array.RHOUSE_Spinner, Android.Resource.Layout.SimpleSpinnerItem);

            adapterhouse.SetDropDownViewResource(Android.Resource.Layout.SimpleListItemActivated1);
            spnrhouse.Adapter = adapterhouse;

            var adpbirthcert = ArrayAdapter.CreateFromResource(
                this, Resource.Array.BirthCertCopy_Spinner, Android.Resource.Layout.SimpleSpinnerItem);

            adpbirthcert.SetDropDownViewResource(Android.Resource.Layout.SimpleListItemActivated1);
            spnbirthcert.Adapter = adpbirthcert;

            var adpmarital = ArrayAdapter.CreateFromResource(
                this, Resource.Array.Marital_Spinner, Android.Resource.Layout.SimpleSpinnerItem);

            adpmarital.SetDropDownViewResource(Android.Resource.Layout.SimpleListItemActivated1);
            spnmarital.Adapter = adpmarital;

            var adpschoolattendance = ArrayAdapter.CreateFromResource(
                this, Resource.Array.SchoolAttend_Spinner, Android.Resource.Layout.SimpleSpinnerItem);

            adpschoolattendance.SetDropDownViewResource(Android.Resource.Layout.SimpleListItemActivated1);
            spnschoolattendance.Adapter = adpschoolattendance;

            var adpschoolhigh = ArrayAdapter.CreateFromResource(
                this, Resource.Array.SchoolHigh_Spinner, Android.Resource.Layout.SimpleSpinnerItem);

            adpschoolhigh.SetDropDownViewResource(Android.Resource.Layout.SimpleListItemActivated1);
            spnschoolhigh.Adapter = adpschoolhigh;

            var adpliteracy = ArrayAdapter.CreateFromResource(
                this, Resource.Array.Literacy_Spinner, Android.Resource.Layout.SimpleSpinnerItem);

            adpliteracy.SetDropDownViewResource(Android.Resource.Layout.SimpleListItemActivated1);
            spnliteracy.Adapter = adpliteracy;

            var adpworkstatus = ArrayAdapter.CreateFromResource(
                this, Resource.Array.WorkStatus_Spinner, Android.Resource.Layout.SimpleSpinnerItem);

            adpworkstatus.SetDropDownViewResource(Android.Resource.Layout.SimpleListItemActivated1);
            spnworkstatus.Adapter = adpworkstatus;

            txtbday.Touch += (sender, e) => {
                if (dialogdate == true)
                {
                    dialogdate = false;
                    var inputView = LayoutInflater.Inflate(Resource.Layout.LayInputDATE, null);
                    var builder   = new AlertDialog.Builder(this);
                    var datep     = (DatePicker)inputView.FindViewById(Resource.Id.datepicker);
                    builder.SetTitle("Cencus");
                    builder.SetMessage("Select Birthday : ");
                    builder.SetView(inputView);
                    builder.SetPositiveButton("Change", OkDialog_Clicked);
                    builder.SetNegativeButton("Cancel", delegate {
                        builder.Dispose();
                    });
                    builder.Show();
                }
                else
                {
                    dialogdate = true;
                }
            };

            btnAddaddress        = FindViewById <Button> (Resource.Id.btnAddAddress);
            btnAddaddress.Click += new EventHandler(btnAddaddress_Clicked);
        }
コード例 #4
0
 private void spawnFilterDialog()
 {
     selectedItems.Add(0);
     selectedItems.Add(1);
     selectedItems.Add(2);
     var builder = new AlertDialog.Builder(ViewContext)
         .SetTitle("Filter Events")
         .SetMultiChoiceItems(items, new bool[] {true,true,true}, MultiListClicked);
     builder.SetPositiveButton("Ok", OkClicked);
     builder.Create();
     builder.Show();
 }
コード例 #5
0
        private void ExportTest()
        {
            if (!ValidateFields())
            {
                return;
            }

            if (!IsExternalStorageWritable())
            {
                var adb = new AlertDialog.Builder(this);
                adb.SetTitle("Export Failed");
                adb.SetMessage("We cannot detect a writable external storage medium for the test. Please ensure the tablet is not plugged into a computer or that the storage is not full");
                adb.SetNegativeButton("Ok.", (sender, e) => {
                });
                adb.Show();
                return;
            }

            Stream stream = null;

            try {
                var now = DateTime.Now;
                var fn  = service.currentTest.testName + " (" + now.ToShortDateString() + " " + now.ToShortTimeString() + ").csv";
                fn = fn.Replace("/", "-");
                var root    = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments);
                var dirPath = System.IO.Path.Combine(root.AbsolutePath, SAVE_PATH);
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                var file = new FileInfo(System.IO.Path.Combine(dirPath, fn));
                stream = file.Open(FileMode.OpenOrCreate);

                if (service.currentTest.Export(stream))
                {
                }
                else
                {
                    var adb = new AlertDialog.Builder(this);
                    adb.SetTitle("Export Failed");
                    adb.SetMessage("Test failed to export");
                    adb.SetNegativeButton("Ok.", (sender, e) => {
                    });
                    adb.Show();
                    return;
                }

                var i = new Intent(Intent.ActionSend);
                i.PutExtra(Intent.ExtraStream, Android.Net.Uri.FromFile(new Java.IO.File(file.FullName)));
                i.SetFlags(ActivityFlags.NewTask | ActivityFlags.NoHistory);
                i.PutExtra(Intent.ExtraEmail, new string[] { sendTo.Text });
                i.PutExtra(Intent.ExtraSubject, "Appion Test Rig Results" + DateTime.Now.ToUTCMilliseconds());
                i.PutExtra(Intent.ExtraText, "The attached CSV is a new ION intial/recalibration test. Please document the attached devices.\n\nRegards,\n" + certifiedBy.Text);
                i.SetType("message/rfc822");

                var chooser = Intent.CreateChooser(i, "Select Send Method");
                chooser.SetFlags(ActivityFlags.NewTask | ActivityFlags.NoHistory);
                StartActivity(chooser);
            } catch (Exception e) {
                var adb = new AlertDialog.Builder(this);
                adb.SetCancelable(false);
                adb.SetTitle("Export Failed");
                adb.SetMessage("Test failed to export:\n" + e.Message + "\n" + e.StackTrace);
                adb.SetNegativeButton("Ok.", (sender, ee) => {
                });
                adb.Show();
            } finally {
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
コード例 #6
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Dialog to display
            LinearLayout dialogView = null;

            // Get the context for creating the dialog controls
            Android.Content.Context ctx = this.Activity.ApplicationContext;

            // Set a dialog title
            this.Dialog.SetTitle("Save Map to Portal");

            try
            {
                base.OnCreateView(inflater, container, savedInstanceState);

                // The container for the dialog is a vertical linear layout
                dialogView             = new LinearLayout(ctx);
                dialogView.Orientation = Orientation.Vertical;

                // Add a text box for entering a title for the new web map
                _mapTitleTextbox      = new EditText(ctx);
                _mapTitleTextbox.Hint = "Title";
                dialogView.AddView(_mapTitleTextbox);

                // Add a text box for entering a description
                _mapDescriptionTextbox      = new EditText(ctx);
                _mapDescriptionTextbox.Hint = "Description";
                dialogView.AddView(_mapDescriptionTextbox);

                // Add a text box for entering tags (populate with some values so the user doesn't have to fill this in)
                _tagsTextbox      = new EditText(ctx);
                _tagsTextbox.Text = "ArcGIS Runtime, Web Map";
                dialogView.AddView(_tagsTextbox);

                // Add a button to save the map
                Button saveMapButton = new Button(ctx);
                saveMapButton.Text   = "Save";
                saveMapButton.Click += SaveMapButtonClick;
                dialogView.AddView(saveMapButton);

                // If there's an existing portal item, configure the dialog for "update" (read-only entries)
                if (this._portalItem != null)
                {
                    _mapTitleTextbox.Text    = this._portalItem.Title;
                    _mapTitleTextbox.Enabled = false;

                    _mapDescriptionTextbox.Text    = this._portalItem.Description;
                    _mapDescriptionTextbox.Enabled = false;

                    _tagsTextbox.Text    = string.Join(",", this._portalItem.Tags);
                    _tagsTextbox.Enabled = false;

                    // Change some of the control text
                    this.Dialog.SetTitle("Save Changes to Map");
                    saveMapButton.Text = "Update";
                }
            }
            catch (Exception ex)
            {
                // Show the exception message
                var alertBuilder = new AlertDialog.Builder(this.Activity);
                alertBuilder.SetTitle("Error");
                alertBuilder.SetMessage(ex.Message);
                alertBuilder.Show();
            }

            // Return the new view for display
            return(dialogView);
        }
コード例 #7
0
ファイル: Detalles.cs プロジェクト: Cesarmhepp/GlucometerV5
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Detalles);

            try
            {
                SidG  = (Intent.GetStringExtra("idG"));
                SiduS = (Intent.GetStringExtra("idUS"));
                idUs  = Convert.ToInt32(SiduS);
                idG   = Convert.ToInt32(SidG);
            }
            catch (Exception ex)
            {
                AlertDialog alerta = new AlertDialog.Builder(this).Create();
                alerta.SetTitle("Error ");
                alerta.SetMessage(ex.Message + "'asdasd'");
                alerta.SetButton("Aceptar", (a, b) => { });
                alerta.Show();
            }
            g = bd.buscar(idG);

            // referencia a obj del laout
            btnfecha        = FindViewById <Button>(Resource.Id.fecha);
            btnfecha.Click += BtnFecha_Click;

            btnDesayunoAntes        = FindViewById <Button>(Resource.Id.btnDesayunoAntes);
            btnDesayunoAntes.Click += BtnDesayunoAntes_Click;
            txt_des_antes           = FindViewById <EditText>(Resource.Id.txt_des_antes);

            btnDesayunoDespues        = FindViewById <Button>(Resource.Id.btnDesayunoDespues);
            btnDesayunoDespues.Click += BtnDesayunoDespues_Click;
            txt_des_Des = FindViewById <EditText>(Resource.Id.txt_des_Des);

            btnAlmuerzoAntes        = FindViewById <Button>(Resource.Id.btnAlmuerzoAntes);
            btnAlmuerzoAntes.Click += BtnAlmuerzoAntes_Click;
            txt_alm_antes           = FindViewById <EditText>(Resource.Id.txt_alm_antes);

            btnAlmuerzoDespues        = FindViewById <Button>(Resource.Id.btnAlmuerzoDespues);
            btnAlmuerzoDespues.Click += BtnAlmuerzoDespues_Click;
            txt_alm_des = FindViewById <EditText>(Resource.Id.txt_alm_des);

            btnAntesCena        = FindViewById <Button>(Resource.Id.btnAntesCena);
            btnAntesCena.Click += BtnAntesCena_Click;
            Txt_cen_Antes       = FindViewById <EditText>(Resource.Id.Txt_cen_Antes);

            btnDespuesCena        = FindViewById <Button>(Resource.Id.btnDespuesCena);
            btnDespuesCena.Click += BtnDespuesCena_Click;
            Txt_cen_Despues       = FindViewById <EditText>(Resource.Id.Txt_cen_Despues);

            btnDormirAntes        = FindViewById <Button>(Resource.Id.btnDormirAntes);
            btnDormirAntes.Click += BtnDormirAntes_Click;
            Txt_Dor_Antes         = FindViewById <EditText>(Resource.Id.Txt_Dor_Antes);

            btnDormirDespues        = FindViewById <Button>(Resource.Id.btnDormirDespues);
            btnDormirDespues.Click += BtnDormirDespues_Click;
            Txt_Dor_Despues         = FindViewById <EditText>(Resource.Id.Txt_Dor_Despues);
            txt_obs = FindViewById <EditText>(Resource.Id.txt_obs);

            // insulina
            mnna_rap    = FindViewById <EditText>(Resource.Id.mnna_rap);
            mnna_regul  = FindViewById <EditText>(Resource.Id.mnna_regul);
            mnna_mezcla = FindViewById <EditText>(Resource.Id.mnna_mezcla);

            tarde_rap    = FindViewById <EditText>(Resource.Id.tarde_rap);
            tarde_regul  = FindViewById <EditText>(Resource.Id.tarde_regul);
            tarde_mezcla = FindViewById <EditText>(Resource.Id.tarde_mezcla);

            noche_rap    = FindViewById <EditText>(Resource.Id.noche_rap);
            noche_regul  = FindViewById <EditText>(Resource.Id.noche_regul);
            noche_mezcla = FindViewById <EditText>(Resource.Id.noche_mezcla);

            dormir_rap            = FindViewById <EditText>(Resource.Id.dormir_rap);
            dormir_regul          = FindViewById <EditText>(Resource.Id.dormir_regul);
            dormir_mezcla         = FindViewById <EditText>(Resource.Id.dormir_mezcla);
            btn_actualizar        = FindViewById <Button>(Resource.Id.btn_actualizar);
            btn_eliminar          = FindViewById <Button>(Resource.Id.btn_eliminar);
            btn_actualizar.Click += ActualizarAsync;
            btn_eliminar.Click   += Btn_eliminar_Click;
            llena_campos();
            SetUpMap();// inicializacion del mapa
        }
コード例 #8
0
        public void PictureTaken(object sender, ProcessedCameraPreview.PictureTakenEventArgs ea)
        {
            Android.Graphics.Bitmap bmp = ea.Bitmap;
            Camera camera = ea.Camera;

            try
            {
                Android.Graphics.Bitmap thumbnail = null;
                int maxThumbnailSize = 96;
                if (_imageFilter == null)
                {
                    _lastSavedImageFile = ProcessedCameraPreview.SaveBitmap(this, bmp, PackageName, _topLayer);
                    thumbnail           = ProcessedCameraPreview.GetThumbnail(bmp, maxThumbnailSize);
                    bmp.Dispose();
                }
                else
                {
                    Image <Bgr, Byte> buffer1 = new Image <Bgr, byte>(bmp);
                    bmp.Dispose();

                    using (ImageFilter filter = _imageFilter.Clone() as ImageFilter)
                    {
                        if (filter is DistorFilter)
                        {
                            //reduce the image size to half because the distor filter used lots of memory
                            Image <Bgr, Byte> tmp = buffer1.PyrDown();
                            buffer1.Dispose();
                            buffer1 = tmp;
                        }

                        if (filter.InplaceCapable)
                        {
                            filter.ProcessData(buffer1.Mat, buffer1.Mat);
                        }
                        else
                        {
                            Image <Bgr, Byte> buffer2 = new Image <Bgr, byte>(buffer1.Size);
                            filter.ProcessData(buffer1.Mat, buffer2.Mat);
                            buffer1.Dispose();
                            buffer1 = buffer2;
                        }
                    }

                    using (Android.Graphics.Bitmap result = buffer1.ToBitmap())
                    {
                        buffer1.Dispose();
                        _lastSavedImageFile = ProcessedCameraPreview.SaveBitmap(this, result, PackageName, _topLayer);
                        thumbnail           = ProcessedCameraPreview.GetThumbnail(result, maxThumbnailSize);
                    }
                }

                _lastCapturedImageButton.SetImageBitmap(thumbnail);
            }
            catch (Exception excpt)
            {
                this.RunOnUiThread(() =>
                {
                    while (excpt.InnerException != null)
                    {
                        excpt = excpt.InnerException;
                    }
                    AlertDialog.Builder alert = new AlertDialog.Builder(this);
                    alert.SetTitle("Error saving file");
                    alert.SetMessage(excpt.Message);
                    alert.SetPositiveButton("OK", (s, er) => { });
                    alert.Show();
                });
                return;
            }

            /*
             * catch (FileNotFoundException e)
             * {
             * Android.Util.Log.Debug("Emgu.CV", e.Message);
             * }
             * catch (IOException e)
             * {
             * Android.Util.Log.Debug("Emgu.CV", e.Message);
             * } */

            /*
             * try
             * {
             * ExifInterface exif = new ExifInterface(f.FullName);
             * // Read the camera model and location attributes
             * exif.GetAttribute(ExifInterface.TagModel);
             * float[] latLng = new float[2];
             * exif.GetLatLong(latLng);
             * // Set the camera make
             * exif.SetAttribute(ExifInterface.TagMake, "My Phone");
             * exif.SetAttribute(ExifInterface.TagDatetime, System.DateTime.Now.ToString());
             * }
             * catch (IOException e)
             * {
             * Android.Util.Log.Debug("Emgu.CV", e.Message);
             * }*/


            Toast.MakeText(this, "File Saved.", ToastLength.Short).Show();
            camera.StartPreview();
        }
コード例 #9
0
        public override Task <string> RunVoicePromptAsync(string prompt, Action postDisplayCallback)
        {
            return(Task.Run(() =>
            {
                string input = null;
                ManualResetEvent dialogDismissWait = new ManualResetEvent(false);

                RunActionUsingMainActivityAsync(mainActivity =>
                {
                    mainActivity.RunOnUiThread(() =>
                    {
                        #region set up dialog
                        TextView promptView = new TextView(mainActivity)
                        {
                            Text = prompt, TextSize = 20
                        };
                        EditText inputEdit = new EditText(mainActivity)
                        {
                            TextSize = 20
                        };
                        LinearLayout scrollLayout = new LinearLayout(mainActivity)
                        {
                            Orientation = global::Android.Widget.Orientation.Vertical
                        };
                        scrollLayout.AddView(promptView);
                        scrollLayout.AddView(inputEdit);
                        ScrollView scrollView = new ScrollView(mainActivity);
                        scrollView.AddView(scrollLayout);

                        AlertDialog dialog = new AlertDialog.Builder(mainActivity)
                                             .SetTitle("Sensus is requesting input...")
                                             .SetView(scrollView)
                                             .SetPositiveButton("OK", (o, e) =>
                        {
                            input = inputEdit.Text;
                        })
                                             .SetNegativeButton("Cancel", (o, e) =>
                        {
                        })
                                             .Create();

                        dialog.DismissEvent += (o, e) =>
                        {
                            dialogDismissWait.Set();
                        };

                        ManualResetEvent dialogShowWait = new ManualResetEvent(false);

                        dialog.ShowEvent += (o, e) =>
                        {
                            dialogShowWait.Set();

                            if (postDisplayCallback != null)
                            {
                                postDisplayCallback();
                            }
                        };

                        // dismiss the keyguard when dialog appears
                        dialog.Window.AddFlags(global::Android.Views.WindowManagerFlags.DismissKeyguard);
                        dialog.Window.AddFlags(global::Android.Views.WindowManagerFlags.ShowWhenLocked);
                        dialog.Window.AddFlags(global::Android.Views.WindowManagerFlags.TurnScreenOn);
                        dialog.Window.SetSoftInputMode(global::Android.Views.SoftInput.AdjustResize | global::Android.Views.SoftInput.StateAlwaysHidden);

                        // dim whatever is behind the dialog
                        dialog.Window.AddFlags(global::Android.Views.WindowManagerFlags.DimBehind);
                        dialog.Window.Attributes.DimAmount = 0.75f;

                        dialog.Show();
                        #endregion

                        #region voice recognizer
                        Task.Run(() =>
                        {
                            // wait for the dialog to be shown so it doesn't hide our speech recognizer activity
                            dialogShowWait.WaitOne();

                            // there's a slight race condition between the dialog showing and speech recognition showing. pause here to prevent the dialog from hiding the speech recognizer.
                            Thread.Sleep(1000);

                            Intent intent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
                            intent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
                            intent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1500);
                            intent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1500);
                            intent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 15000);
                            intent.PutExtra(RecognizerIntent.ExtraMaxResults, 1);
                            intent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default);
                            intent.PutExtra(RecognizerIntent.ExtraPrompt, prompt);

                            mainActivity.GetActivityResultAsync(intent, AndroidActivityResultRequestCode.RecognizeSpeech, result =>
                            {
                                if (result != null && result.Item1 == Result.Ok)
                                {
                                    IList <string> matches = result.Item2.GetStringArrayListExtra(RecognizerIntent.ExtraResults);
                                    if (matches != null && matches.Count > 0)
                                    {
                                        mainActivity.RunOnUiThread(() =>
                                        {
                                            inputEdit.Text = matches[0];
                                        });
                                    }
                                }
                            });
                        });
                        #endregion
                    });
                }, true, false);

                dialogDismissWait.WaitOne();

                return input;
            }));
        }
コード例 #10
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            ActionBar.SetDisplayHomeAsUpEnabled(true);
            ActionBar.SetHomeButtonEnabled(true);

            SetContentView(Resource.Layout.activity_test);
            handler = new Handler(Looper.MainLooper);

            state                = FindViewById <TextView>(Resource.Id.state);
            startTest            = FindViewById <Button>(Resource.Id.startTest);
            startTest.Visibility = ViewStates.Gone;
            startTest.Click     += async(sender, e) => {
                if (test.isTesting)
                {
                    StopTest();
                }
                else
                {
                    await StartTest();
                }
            };


            var rawSerials = Intent.GetStringArrayExtra(EXTRA_SERIALS);
            var type       = (EDeviceModel)Intent.GetIntExtra(EXTRA_TEST_TYPE, -1);

            if (rawSerials == null)
            {
                var adb = new AlertDialog.Builder(this);
                adb.SetTitle("Initialization Error");
                adb.SetMessage("Failed to start TestActivity: no serial numbers were passed to the activity");
                adb.SetNegativeButton("Cancel", (sender, e) => {
                    Finish();
                });
                adb.Show();
            }

            var sns = new List <ISerialNumber>();

            foreach (var raw in rawSerials)
            {
                var sn = raw.ParseSerialNumber();
                if (sn.deviceModel != type)
                {
                    var adb = new AlertDialog.Builder(this);
                    adb.SetTitle("Initialization Error");
                    adb.SetMessage("Failed to start TestActivity: serial number type (" + sn.deviceModel + ") is not the expected: " + type);
                    adb.SetNegativeButton("Well, that sucks", (sender, e) => {
                        Finish();
                    });
                    adb.Show();
                    return;
                }
                else
                {
                    sns.Add(sn);
                }
            }

            grid       = FindViewById <DSGridView>(Resource.Id.grid);
            grid.Theme = DSoft.Themes.Grid.DSGridTheme.Current;

            Initialize();

            UpdateStartTestButton();
        }
コード例 #11
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            int checkedBoxes = 0;
            int maxChecked   = 0;
            int minChecked   = 0;
            int click        = 0;

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.QuestionBase);
            var baseLayout = FindViewById <LinearLayout>(Resource.Id.outer);
            // Get our button from the layout resource,
            // and attach an event to it
            Button buttonBack = FindViewById <Button>(Resource.Id.buttonNext);

            buttonBack.Click += delegate
            {
                Finish();
            };
            TextView      textTitle      = FindViewById <TextView>(Resource.Id.textTitle);
            Reader        reader         = new Reader();
            string        qtiPath        = (string)Intent.Extras.Get("qtiPath");
            Stream        strm           = Assets.Open(qtiPath);
            XDocument     qFile          = XDocument.Load(strm);
            AssesmentItem assessmentItem = reader.Main(qFile);

            List <VariableDeclaration> declarations = assessmentItem.declerations;
            List <Block> itemBody = assessmentItem.itemBody;

            textTitle.Text = assessmentItem.title;
            foreach (Block b in itemBody)
            {
                switch (b.GetType().Name)
                {
                    #region ChoiceInteraction
                case "ChoiceInteraction":
                    ChoiceInteraction block        = (b as ChoiceInteraction);
                    LinearLayout      answerLayout = new LinearLayout(this)
                    {
                        LayoutParameters =
                            new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent,
                                                          ViewGroup.LayoutParams.WrapContent, 2f / itemBody.Count),
                        Orientation = Android.Widget.Orientation.Vertical
                    };
                    baseLayout.AddView(answerLayout);
                    TextView textPrompt = new TextView(this);
                    ViewGroup.LayoutParams textLayout = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
                    textPrompt.LayoutParameters = textLayout;
                    textPrompt.TextSize         = 20;
                    textPrompt.Text             = block.prompt;
                    answerLayout.AddView(textPrompt);

                    maxChecked = block.maxChoices;
                    ViewGroup.LayoutParams checkLayout = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
                    if (maxChecked == 1)    //use radio buttons
                    {
                        RadioGroup rGroup = new RadioGroup(this);
                        LinearLayout.LayoutParams rGroupParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
                        rGroup.LayoutParameters = rGroupParams;
                        answerLayout.AddView(rGroup);
                        foreach (Choice c in block.choices)
                        {
                            RadioButton choiceButton = new RadioButton(this);
                            choiceButton.LayoutParameters = checkLayout;
                            choiceButton.Text             = c.body;
                            rGroup.AddView(choiceButton);
                        }
                    }
                    else        //use checkboxes
                    {
                        foreach (Choice c in block.choices)
                        {
                            CheckBox choiceBox = new CheckBox(this);
                            choiceBox.LayoutParameters = checkLayout;
                            choiceBox.Text             = c.body;
                            choiceBox.Click           += (o, e) =>
                            {
                                if (!choiceBox.Checked)
                                {
                                    checkedBoxes--;
                                }
                                else if (checkedBoxes < maxChecked)
                                {
                                    checkedBoxes++;
                                }
                                else if (maxChecked != 0)
                                {
                                    AlertDialog.Builder alertTooMany = new AlertDialog.Builder(this);
                                    alertTooMany.SetTitle("Too Many Selections");
                                    alertTooMany.SetMessage("The maximum amount of selections for this question is: " + maxChecked);
                                    alertTooMany.SetPositiveButton("Okay", (senderAlert, args) =>
                                    {
                                        alertTooMany.Dispose();
                                        choiceBox.Toggle();
                                    });
                                    alertTooMany.SetCancelable(false);
                                    alertTooMany.Show();
                                }
                            };
                            answerLayout.AddView(choiceBox);
                        }
                    }
                    break;

                    #endregion
                case "Block":
                    LinearLayout blockLayout = new LinearLayout(this)
                    {
                        LayoutParameters =
                            new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent,
                                                          0, 1f / itemBody.Count),
                        Orientation = Android.Widget.Orientation.Horizontal
                    };
                    baseLayout.AddView(blockLayout);
                    foreach (BlockElement e in b.blockElements)
                    {
                        if ((e as P).inline.GetType().Name == "Image")     // add an image block
                        {
                            ImageView image      = new ImageView(this);
                            Inline    target     = (e as P).inline;
                            string    imgSrc     = (target as Image).source;
                            var       resourceId = (int)typeof(Resource.Drawable).GetField(imgSrc).GetValue(null);
                            image.SetImageResource(resourceId);
                            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
                            layoutParams.Gravity   = GravityFlags.Center;
                            image.LayoutParameters = layoutParams;
                            image.Click           += (o, x) =>
                            {
                                ImageView bigImage = new ImageView(this);
                                bigImage.SetImageResource(resourceId);
                                LinearLayout.LayoutParams layoutParamsBig = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
                                layoutParams.Gravity      = GravityFlags.CenterHorizontal;
                                bigImage.LayoutParameters = layoutParamsBig;
                                bigImage.Click           += (a, c) =>
                                {
                                    SetContentView(baseLayout);
                                };
                                SetContentView(bigImage);
                            };
                            blockLayout.AddView(image);
                        }
                        else if ((e as P).inline.GetType().Name == "Inline")     // add a text block
                        {
                            TextView inlineText = new TextView(this);
                            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
                            layoutParams.Gravity        = GravityFlags.Center;
                            inlineText.LayoutParameters = layoutParams;
                            inlineText.Text             = (e as P).inline.content;
                            inlineText.TextSize         = 15;
                            blockLayout.AddView(inlineText);
                        }
                    }
                    break;

                default:
                    //textFlavour.Text += b.GetType().Name + "\n";
                    break;
                }
            }
            //textPrompt.Text = (itemBody[2] as ChoiceInteraction).prompt;
            //string res= "";
            //foreach (Choice c in (itemBody[2] as ChoiceInteraction).choices)
            //{
            //    res += c.ToString() + "\n";
            //}
            //textChoices.Text = res;

            //};
        }
コード例 #12
0
        public void ShowHelpIfNecessary(TutorialHelper tutorial, Action dismissed = null)
        {
            if (CrossSettings.Current.GetValueOrDefault(tutorial.Id, false))
            {
                dismissed?.Invoke();
                return;
            }
            CrossSettings.Current.AddOrUpdateValue(tutorial.Id, true);


            View view = LayoutInflater.Inflate(Resource.Layout.TutorialLayout, null);

            ActivityExtensions.SetViewFont(view as ViewGroup);

            var lblTitle    = view.FindViewById <TextView>(Resource.Id.lblTitle);
            var lblSubtitle = view.FindViewById <TextView>(Resource.Id.lblSubtitle);
            var imgImage    = view.FindViewById <ImageView>(Resource.Id.imgImage);
            var btnOk       = view.FindViewById <Button>(Resource.Id.btnOk);
            var id          = Resources.GetIdentifier(tutorial.AndroidIcon.ToLower(), "drawable", PackageName);

            imgImage.SetImageResource(id);

            lblTitle.Text = tutorial.Title;

            btnOk.Typeface    = CustomTypefaces.RobotoBold;
            lblTitle.Typeface = CustomTypefaces.RobotoBold;

            btnOk.Text = tutorial.ButtonText;

            if (tutorial.Id == "Welcome")
            {
                var span = new SpannableString(tutorial.Title);
                span.SetSpan(new FanwordTypefaceSpan(CustomTypefaces.RobotoBold), 8, tutorial.Title.Length, SpanTypes.ExclusiveExclusive);
                span.SetSpan(new ForegroundColorSpan(new Color(249, 95, 6)), 8, tutorial.Title.Length, SpanTypes.ExclusiveExclusive);
                lblTitle.TextFormatted = span;
            }

            lblSubtitle.Text = tutorial.Subtitle;

            var dialog = new AlertDialog.Builder(this).SetView(view).Create();

            if (btnOk.Text == "Follow Profiles")
            {
                btnOk.Click += (sender, e) =>
                {
                    dialog.Dismiss();
                    StartActivity(typeof(SearchActivity));
                };
            }
            else
            {
                btnOk.Click += (sender, e) =>
                {
                    dialog.Dismiss();
                };
            }


            dialog.DismissEvent += (sender, e) =>
            {
                dismissed?.Invoke();
            };

            dialog.Show();
        }
コード例 #13
0
        //int count = 1;

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

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button   TranslateButton = FindViewById <Button> (Resource.Id.TRANSLATENUMBER);
            Button   CallButton      = FindViewById <Button>(Resource.Id.CALL);
            Button   CnButton        = FindViewById <Button>(Resource.Id.CNBUTTON);
            EditText PhoneNumberText = FindViewById <EditText>(Resource.Id.PHONENUMBEREDIT);
            TextView RemindInfo      = FindViewById <TextView>(Resource.Id.REMINDTEXT);

            CallButton.Enabled = false;

            string strTarget = string.Empty;

            TranslateButton.Click += (object sender, EventArgs e) => {
                strTarget = TranslatePhone.ToNumberOrTranslate(PhoneNumberText.Text);
                if (string.IsNullOrWhiteSpace(strTarget))
                {
                    CallButton.Text    = "Call";
                    CallButton.Enabled = false;
                    return;
                }
                CallButton.Text    = "Call " + strTarget + " now?";
                CallButton.Enabled = true;
            };
            CallButton.Click += delegate
            {
                var alertDlg = new AlertDialog.Builder(this);
                alertDlg.SetMessage("Intend to call " + strTarget + ", are you sure???");
                alertDlg.SetNeutralButton("yes", delegate
                {
                    Android.Net.Uri uri = Android.Net.Uri.Parse("tel:" + strTarget);
                    Intent intent       = new Intent(Intent.ActionCall, uri);
                    StartActivity(intent);
                }
                                          );
                alertDlg.SetNegativeButton("no", delegate { });
                alertDlg.Show();
            };



            //java android 发短信,打电话
            //class SendMsgClickListener implements OnClickListener
            //        {
            //        public void onClick(View v)
            //        {
            //            //调用Android系统API发送短信
            //            Uri uri = Uri.parse("smsto:15800001234");
            //            Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
            //            intent.putExtra("sms_body", "android...");
            //            startActivity(intent);
            //        }
            //    }

            //    //打电话
            //    class SendCallClickListener implements OnClickListener
            //    {
            //        iphone5
            //        public void onClick(View v)
            //    {
            //        //调用Android系统API打电话
            //        Uri uri = Uri.parse("tel:15800001234");
            //        Intent intent = new Intent(Intent.ACTION_CALL, uri);
            //        startActivity(intent);
            //    }
            //}
            //2. [代码]
            //最后不要忘了做这些操作是需要授权的,需要在AndroidManifest.xml中加入两行配置
            //?
            //1
            //2
            //<uses-permission android:name="android.permission.CALL_PHONE" />
            //<uses-permission android:name="android.permission.SEND_SMS"/>
        }
コード例 #14
0
ファイル: MindMap.cs プロジェクト: yo1249009/xamarin-demos
        internal void ShowPopUp(string positive, string negative)
        {
            alertBuilder.SetTitle("Enter Text");
            editText.Text = _inputstring;
            editText.FocusableInTouchMode = true;
            editText.RequestFocus();
            editText.SetBackgroundColor(Color.WhiteSmoke);
            editText.SetTextColor(Color.Black);
            alertBuilder.SetView(editText);
            alertBuilder.SetCancelable(false);

            alertBuilder.SetPositiveButton(positive, (senderAlert, args) =>
            {
                diagram.Alpha = 1;
                diagram.PageSettings.BackgroundColor = Color.White;
                if (editText.Text == null)
                {
                    editText.Text = "";
                }
                var node = new Node(diagram.Context);
                if (CurrentHandle == UserHandlePosition.Left)
                {
                    node.OffsetX = SelectedNode.OffsetX - SelectedNode.Width - 100;
                    node.OffsetY = SelectedNode.OffsetY;
                }
                else if (CurrentHandle == UserHandlePosition.Right)
                {
                    node.OffsetX = SelectedNode.OffsetX + SelectedNode.Width + 100;
                    node.OffsetY = SelectedNode.OffsetY;
                }
                node.Width             = SelectedNode.Width;
                node.Height            = SelectedNode.Height;
                node.ShapeType         = ShapeType.RoundedRectangle;
                node.Style.StrokeWidth = 3;
                if (SelectedNode == RootNode)
                {
                    index                  = rnd.Next(5);
                    node.Style.Brush       = new SolidBrush(FColor[index]);
                    node.Style.StrokeBrush = new SolidBrush(SColor[index]);
                }
                else
                {
                    node.Style = SelectedNode.Style;
                }
                node.Annotations.Add(new Annotation()
                {
                    Content = editText.Text, FontSize = 14 * MainActivity.Factor, TextBrush = new SolidBrush(Color.Black)
                });
                diagram.AddNode(node);
                var c1        = new Connector(diagram.Context);
                c1.SourceNode = SelectedNode;
                c1.TargetNode = node;
                //c1.Style.StrokeBrush = node.Style.StrokeBrush;
                //c1.Style.StrokeWidth = 3;
                //c1.TargetDecoratorStyle.Fill = (node.Style.StrokeBrush as SolidBrush).FillColor;
                //c1.TargetDecoratorStyle.StrokeColor = (c1.TargetNode.Style.StrokeBrush as SolidBrush).FillColor;
                //c1.SegmentType = SegmentType.CurveSegment;
                //c1.Style.StrokeStyle = StrokeStyle.Dashed;
                diagram.AddConnector(c1);
                if (CurrentHandle == UserHandlePosition.Left)
                {
                    if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm)
                    {
                        (diagram.LayoutManager.Layout as MindMapLayout).UpdateLeftOrTop();
                    }
                }
                else if (CurrentHandle == UserHandlePosition.Right)
                {
                    if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm)
                    {
                        (diagram.LayoutManager.Layout as MindMapLayout).UpdateRightOrBottom();
                    }
                }
                m_mindmap.SelectedNode = node;
                m_mindmap.UpdateHandle();
                diagram.Select(node);

                diagram.BringToView(node);
                m_mindmap.UpdateTheme();
            });
            alertBuilder.SetNegativeButton(negative, (senderAlert, args) =>
            {
                alertBuilder.SetCancelable(true);
            });
            alertBuilder.Show();
        }
コード例 #15
0
        private void ForgotOnClick(object sender, EventArgs eventArgs)
        {
            /*
             * var alert = new AlertDialog.Builder(this);
             * alert.SetTitle("Oh ne!");
             * alert.SetPositiveButton("U redu", (o, args) => { alert.Dispose(); });
             *
             * alert.SetMessage("Nista ne brinite!\n\nRadi resetovanja sifre, javite se nasem adminu na mail:\n\[email protected]");
             *
             * alert.Show();
             */

            var inflater = LayoutInflater.From(this);
            var view     = inflater.Inflate(Resource.Layout.forgotDialog, null);

            var dialogForgot = new AlertDialog.Builder(this);
            var dialogPin    = new AlertDialog.Builder(this);
            var alertUspesno = new AlertDialog.Builder(this);

            var    username = view.FindViewById <TextView>(Resource.Id.forgotUsername);
            string ime      = "";

            dialogForgot.SetView(view);

            dialogForgot.SetPositiveButton("Resetuj", delegate(object o, DialogClickEventArgs args)
            {
                if (!username.Text.Equals(String.Empty))
                {
                    ime = username.Text;
                    try
                    {
                        //Api.Api.ZaboravljenaSifra(ime);
                        dialogForgot.Dispose();

                        var alert = new AlertDialog.Builder(this);
                        alert.SetTitle("Resetovanje!");
                        alert.SetMessage("Proverite Vas mail kako bi ste dobili PIN za reset.\n" +
                                         "Pin ukucajte na sledecoj formi.");
                        alert.SetPositiveButton("U redu", (ooo, argsss) =>
                        {
                            alert.Dispose();
                            dialogPin.Show();
                        });

                        alert.Show();
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
                        dialogForgot.Dispose();
                    }
                }
                else
                {
                    Toast.MakeText(this, "Unesite korisnicko ime!", ToastLength.Short).Show();
                }
            });

            dialogForgot.SetNegativeButton("Unesi PIN", delegate(object o, DialogClickEventArgs args)
            {
                dialogForgot.Dispose();
                dialogPin.Show();
            });


            var view2 = inflater.Inflate(Resource.Layout.pinDialog, null);

            dialogPin.SetView(view2);

            dialogPin.SetPositiveButton("Potvrdi", delegate(object o, DialogClickEventArgs args)
            {
                var pin       = view2.FindViewById <TextView>(Resource.Id.pin);
                var sifra     = view2.FindViewById <TextView>(Resource.Id.pinNovaSifra);
                var sifraOpet = view2.FindViewById <TextView>(Resource.Id.pinNovaSifraOpet);

                if (sifra.Text.Equals(sifraOpet.Text) && !pin.Text.Equals(String.Empty))
                {
                    PassRecoveryDto noviPass = new PassRecoveryDto()
                    {
                        Pin           = pin.Text,
                        KorisnickoIme = ime,
                        NovaSifra     = sifra.Text
                    };

                    try
                    {
                        // Api.Api.OporavakSifre(noviPass);
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
                        dialogPin.Dispose();
                    }
                }
                else
                {
                    if (!pin.Text.Equals(String.Empty))
                    {
                        Toast.MakeText(this, "Unesite PIN!", ToastLength.Short).Show();
                    }
                    else
                    {
                        Toast.MakeText(this, "Sifre se ne poklapaju!", ToastLength.Short).Show();
                    }
                }
            });

            alertUspesno.SetTitle("Obavestenje!");
            alertUspesno.SetMessage("Uspesno ste resetovali Vasu sifru!");
            alertUspesno.SetPositiveButton("U redu", (o, args) => alertUspesno.Dispose());

            dialogForgot.Show();
        }
コード例 #16
0
 private void OnClicked(object sender, EventArgs args)
 {
     AlertDialog.Builder builder = new AlertDialog.Builder(currentContext);
     builder.SetSingleChoiceItems(nativeCell.Items.ToArray(), nativeCell.SelectedIndex, AlertDialogHandler);
     builder.Show();
 }
コード例 #17
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            EditText userid          = FindViewById <EditText>(Resource.Id.EditText_userID);
            EditText password        = FindViewById <EditText>(Resource.Id.EditText_Password);
            EditText location        = FindViewById <EditText>(Resource.Id.EditText_Location);
            EditText date            = FindViewById <EditText>(Resource.Id.EditText_Date);
            EditText time            = FindViewById <EditText>(Resource.Id.EditText_Time);
            Button   button          = FindViewById <Button>(Resource.Id.Button_setavail);
            Button   button2         = FindViewById <Button>(Resource.Id.Button_setnotavail);
            Button   button3         = FindViewById <Button>(Resource.Id.Button_getstatus);
            Button   btnGoToTracking = FindViewById <Button>(Resource.Id.btnGoToTracking);

            TMSNextLevel.webrefMStrongCreates.WebService client = new TMSNextLevel.webrefMStrongCreates.WebService();

            userid.Text   = prefs.GetString("strUserID", null);
            password.Text = prefs.GetString("strPassword", null);

            btnGoToTracking.Click += delegate
            {
                StartActivity(new Intent(this.ApplicationContext, typeof(Secondary)));
                Finish();
            };

            button.Click += delegate    // set driver avail
            {
                ISharedPreferencesEditor editor = prefs.Edit();
                editor.PutString("strUserID", userid.Text);
                editor.PutString("strPassword", password.Text);
                editor.Apply();

                ProgressDialog progressDialog = ProgressDialog.Show(this, "Loading...", "checking account info...", true);
                var            dialogRunning  = 1;

                Task.Run(() =>
                {
                    Thread.Sleep(20000);
                    if (dialogRunning == 1)
                    {
                        RunOnUiThread(() =>
                        {
                            AlertDialog.Builder ad = new AlertDialog.Builder(this);
                            ad.SetTitle("Failed");
                            ad.SetMessage("Operation Timed Out. Service Unreachable.");
                            ad.Show();
                            progressDialog.Dismiss();
                        });
                    }
                });
                Task.Run(() =>
                {
                    var result = client.SetDriverAvail(userid.Text, password.Text, location.Text, date.Text + time.Text);
                    RunOnUiThread(() =>
                    {
                        if (result == 1)
                        {
                            AlertDialog.Builder ad = new AlertDialog.Builder(this);
                            ad.SetTitle("Success");
                            ad.SetMessage("You are now set to Available.");
                            ad.Show();
                            dialogRunning = 0;
                        }
                        else
                        {
                            AlertDialog.Builder ad = new AlertDialog.Builder(this);
                            ad.SetTitle("Failed");
                            ad.SetMessage("Please check your login credentials. Location, Date, and Time are required.");
                            ad.Show();
                            dialogRunning = 0;
                        }
                        progressDialog.Dismiss();
                    });
                });
            };

            button2.Click += delegate
            {
                ISharedPreferencesEditor editor = prefs.Edit();
                editor.PutString("strUserID", userid.Text);
                editor.PutString("strPassword", password.Text);
                editor.Apply();

                ProgressDialog progressDialog = ProgressDialog.Show(this, "Loading...", "checking account info...", true);
                var            dialogRunning  = 1;

                Task.Run(() =>
                {
                    Thread.Sleep(20000);
                    if (dialogRunning == 1)
                    {
                        RunOnUiThread(() =>
                        {
                            AlertDialog.Builder ad = new AlertDialog.Builder(this);
                            ad.SetTitle("Failed");
                            ad.SetMessage("Operation Timed Out. Service Unreachable.");
                            ad.Show();
                            progressDialog.Dismiss();
                        });
                    }
                });
                Task.Run(() =>
                {
                    var result = client.SetDriverNotAvail(userid.Text, password.Text);
                    RunOnUiThread(() =>
                    {
                        if (result == 1)
                        {
                            AlertDialog.Builder ad = new AlertDialog.Builder(this);
                            ad.SetTitle("Success");
                            ad.SetMessage("You are now set to NOT available.");
                            ad.Show();
                            dialogRunning = 0;
                        }
                        else
                        {
                            AlertDialog.Builder ad = new AlertDialog.Builder(this);
                            ad.SetTitle("Failed");
                            ad.SetMessage("Please check your login credentials.");
                            ad.Show();
                            dialogRunning = 0;
                        }
                        progressDialog.Dismiss();
                    });
                });
            };

            button3.Click += delegate    // GET STATUS
            {
                ISharedPreferencesEditor editor = prefs.Edit();
                editor.PutString("strUserID", userid.Text);
                editor.PutString("strPassword", password.Text);
                editor.Apply();

                ProgressDialog progressDialog = ProgressDialog.Show(this, "Loading...", "checking account info...", true);
                var            dialogRunning  = 1;

                Task.Run(() =>     // RUN TIMEOUT CHECKER
                {
                    Thread.Sleep(20000);
                    if (dialogRunning == 1)
                    {
                        RunOnUiThread(() =>
                        {
                            AlertDialog.Builder ad = new AlertDialog.Builder(this);
                            ad.SetTitle("Failed");
                            ad.SetMessage("Operation Timed Out. Service Unreachable.");
                            ad.Show();
                            progressDialog.Dismiss();
                        });
                    }
                });

                Task.Run(() =>   // RUN WebService call in Thread, once returned display Dialog
                {
                    var result = client.GetStatus(userid.Text, password.Text);
                    RunOnUiThread(() =>
                    {
                        AlertDialog.Builder ad = new AlertDialog.Builder(this);
                        ad.SetTitle("TMS Next Level");
                        ad.SetMessage(result);
                        ad.Show();
                        progressDialog.Dismiss();
                        dialogRunning = 0;
                    });
                });
            };

            date.Click += (sender, e) =>
            {
                DateTime         today  = DateTime.Today;
                DatePickerDialog dialog = new DatePickerDialog(this, OnDateSet, today.Year, today.Month - 1, today.Day);
                dialog.Show();
            };

            void OnDateSet(object sender, DatePickerDialog.DateSetEventArgs e)
            {
                string varTime = e.Date.ToString();

                varTime   = varTime.Remove(varTime.Length - 11);
                date.Text = varTime;
            }

            time.Click += (sender, e) =>
            {
                DateTime         today  = DateTime.Today;
                TimePickerDialog dialog = new TimePickerDialog(this, OnDateSet2, today.Hour, today.Minute, false);
                dialog.Show();
            };

            void OnDateSet2(object sender, TimePickerDialog.TimeSetEventArgs e)
            {
                string hours = e.HourOfDay.ToString();

                if (e.HourOfDay < 10)
                {
                    hours = "0" + e.HourOfDay;
                }
                if (e.Minute < 10)
                {
                    time.Text = hours + ":0" + e.Minute;
                }
                else
                {
                    time.Text = hours + ":" + e.Minute;
                }
            }
        }
コード例 #18
0
/*
 *              public override void OnServiceBound() {
 *                      base.OnServiceBound();
 *                      Initialize();
 *              }
 */

        private void Initialize()
        {
            var rawSerials = Intent.GetStringArrayExtra(EXTRA_SERIALS);
            var type       = (EDeviceModel)Intent.GetIntExtra(EXTRA_TEST_TYPE, -1);

            if (rawSerials == null)
            {
                var adb = new AlertDialog.Builder(this);
                adb.SetTitle("Initialization Error");
                adb.SetMessage("Failed to start TestActivity: no serial numbers were passed to the activity");
                adb.SetCancelable(false);
                adb.SetNegativeButton("Cancel", (sender, e) => {
                    Finish();
                });
                adb.Show();
                return;
            }

            var sns = new List <ISerialNumber>();

            foreach (var raw in rawSerials)
            {
                var sn = raw.ParseSerialNumber();
                if (sn.deviceModel != type)
                {
                    var adb = new AlertDialog.Builder(this);
                    adb.SetTitle("Initialization Error");
                    adb.SetMessage("Failed to start TestActivity: serial number type (" + sn.deviceModel + ") is not the expected: " + type);
                    adb.SetCancelable(false);
                    adb.SetNegativeButton("Well, that sucks", (sender, e) => {
                        Finish();
                    });
                    adb.Show();
                    return;
                }
                else
                {
                    sns.Add(sn);
                }
            }

            if (sns.Count <= 0)
            {
                var adb = new AlertDialog.Builder(this);
                adb.SetTitle("Initialization Error");
                adb.SetMessage("No serial numbers were provided to the TestActivity.");
                adb.SetCancelable(false);
                adb.SetNegativeButton("Ok. Take me to my leaders", (sender, e) => {
                    Finish();
                });
                adb.Show();
                return;
            }

            if (BuildTest(sns))
            {
                InitGrid();
                UpdateStartTestButton();
            }

            handler.PostDelayed(() => grid.ReloadData(), 1500);
        }
コード例 #19
0
        // Retrieve a list of conversations
        private User[] GetFriends()
        {
            // send the server the user name
            // server side does the selection and return the other users' names/id and store it in a user array.
            //Send the login username and password to the server and get response
            string apiUrl    = "https://ycandgap.me/api_server2.php";
            string apiMethod = "getFriends";

            //Login_Request has two properties:username and password
            Login_Request myLogin_Request = new Login_Request();
            //get the login username from previow login page.
            ISharedPreferences sharedPref = PreferenceManager.GetDefaultSharedPreferences(this);

            myLogin_Request.RegistrationID = Convert.ToUInt32(sharedPref.GetString("RegistrationId", string.Empty));


            // make http post request
            string response = Http.Post(apiUrl, new NameValueCollection()
            {
                { "api_method", apiMethod },
                { "api_data", JsonConvert.SerializeObject(myLogin_Request) }
            });

            // decode json string to dto object
            API_Response1 r = JsonConvert.DeserializeObject <API_Response1>(response);

            // check response
            if (r != null)
            {
                if (!r.IsError)
                {
                    if (r.Array != null)
                    {
                        MessagesActivity m           = new MessagesActivity();
                        List <User>      friends     = new List <User>();
                        string           lastmessage = string.Empty;
                        //(m.GetMessages(sharedPref) != null) ? m.GetMessages(sharedPref).FirstOrDefault().MessageText : string.Empty;
                        foreach (Friend friend in r.Array)
                        {
                            friends.Add(new User()
                            {
                                IdentityKey           = friend.IdentityKey,
                                LastMessage           = lastmessage,
                                RegisterationID       = Convert.ToUInt32(friend.RegistrationID),
                                SignedPreKeyID        = Convert.ToUInt32(friend.SignedPreKeyID),
                                SignedPreKeySignature = friend.SignedPreKeySignature,
                                SignedPreKey          = friend.SignedPreKey,
                                Username = friend.Username
                            });
                        }
                        return(friends.ToArray());
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    //if login fails, pop up an alert message. Wrong username or password or a new user
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
                    dialogBuilder.SetMessage(r.ErrorMessage);
                    //dialogBuilder.SetPositiveButton("Ok", null);
                    dialogBuilder.Show();
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
コード例 #20
0
        private bool BuildTest(List <ISerialNumber> serialNumbers)
        {
            var address = Intent.GetStringExtra(EXTRA_RIG_ADDRESS);
            var type    = (EDeviceModel)Intent.GetIntExtra(EXTRA_TEST_TYPE, -1);

            service = AppService.INSTANCE;
            var rig = service.GetRigByAddress(address);

            if (rig == null)
            {
                var adb = new AlertDialog.Builder(this);
                adb.SetTitle("Initialization Error");
                adb.SetMessage("Failed to find Rig.");
                adb.SetCancelable(false);
                adb.SetNegativeButton("Then how did I get here? Ok, take me back...", (sender, e) => {
                    Finish();
                });
                adb.Show();
                return(false);
            }
            else if (rig.rigType != type.AsRigType())
            {
                var adb = new AlertDialog.Builder(this);
                adb.SetTitle("Initialization Error");
                adb.SetMessage("Received a Rig of type: " + rig.rigType + ". A rig of this type is incompatible with a test designed for " + type);
                adb.SetCancelable(false);
                adb.SetNegativeButton("This app just refuses to work. Ok, take me back...", (sender, e) => {
                    Finish();
                });
                adb.Show();
                return(false);
            }
            else
            {
                var connections = new List <IConnection>();

                foreach (var serialNumber in serialNumbers)
                {
                    // TODO [email protected]: This is bad
                    var connection = service.GetConnection(serialNumber);
                    if (connection != null)
                    {
                        connections.Add(connection);
                    }
                }

                var tp = new XmlTestParser().Parse(EmbeddedResource.Load(typeof(TestActivity).GetTypeInfo().Assembly, "test_av760.xml"));
                switch (rig.rigType)
                {
                case ERigType.Vacuum:
                    test = new AV760Test(tp, rig as VacuumRig, connections);
                    break;

                default:
                    var adb = new AlertDialog.Builder(this);
                    adb.SetTitle("Initialization Error");
                    adb.SetMessage("Failed to build test");
                    adb.SetCancelable(false);
                    adb.SetNegativeButton("Wai?! Ok, take me back...", (sender, e) => {
                        Finish();
                    });
                    adb.Show();
                    return(false);
                }

                service.currentTest = test;
                test.onTestEvent   += OnTestEvent;
                return(true);
            }
        }
コード例 #21
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
            SetContentView(Resource.Layout.Main);

            ActionBar.Tab tabSettings = ActionBar.NewTab();
            ActionBar.Tab tabCalendar = ActionBar.NewTab();
            ActionBar.Tab tabSchedule = ActionBar.NewTab();
            ActionBar.Tab tabEdit     = ActionBar.NewTab();

            tabSettings.SetText("Settings");
            //tab.SetIcon(Resource.Drawable.settingssmall);
            tabSettings.TabSelected += (sender, args) => {
                SetContentView(Resource.Layout.Settings);

                Button   btn_ok;
                EditText text_name;
                EditText text_second_name;
                EditText text_middle_name;
                EditText text_group;

                btn_ok           = FindViewById <Button> (Resource.Id.buttonOk);
                text_name        = FindViewById <EditText> (Resource.Id.editTextName);
                text_second_name = FindViewById <EditText> (Resource.Id.editTextSecondName);
                text_middle_name = FindViewById <EditText> (Resource.Id.editTextMiddleName);
                text_group       = FindViewById <EditText> (Resource.Id.editTextGroup);

                btn_ok.Click += delegate {
                    var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    var filePath      = System.IO.Path.Combine(documentsPath, "private.txt");

                    System.IO.File.WriteAllText(filePath, text_name.Text + "\n" + text_second_name.Text + "\n" + text_middle_name.Text + "\n" + text_group.Text);

                    data = new PersonalData(text_name.Text, text_second_name.Text, text_middle_name.Text, text_group.Text);

                    stream_schedule = new List <ApiInteractionMember> ();

                    tabSchedule.Select();
                };
            };

            ActionBar.AddTab(tabSettings);

            tabCalendar.SetText("Calendar");
            //tab.SetIcon(Resource.Drawable.calendarsmall);
            tabCalendar.TabSelected += (sender, args) => {
                SetContentView(Resource.Layout.Calendar);

                CalendarView calendar = FindViewById <CalendarView> (Resource.Id.calendarView1);

                calendar.DateChange += (object sender_calendar, CalendarView.DateChangeEventArgs e_calendar) =>
                {
                    var day_of_month = e_calendar.DayOfMonth;
                    var current_day  = DateTime.Now.Day;

                    var month         = e_calendar.Month;
                    var current_month = DateTime.Now.Month;

                    addedDays   = day_of_month - current_day;
                    addedMonths = month - current_month;

                    tabSchedule.Select();
                };
            };

            ActionBar.AddTab(tabCalendar);

            tabSchedule.SetText("My Schedule");
            //tab.SetIcon(Resource.Drawable.thirdsmall);
            tabSchedule.TabSelected += (sender, args) => {
                data = getPersonalData();

                SetContentView(Resource.Layout.Schedule);

                ListView listView;

                listView = FindViewById <ListView> (Resource.Id.listView1);

                DateTime current_date = DateTime.Now.AddDays(addedDays);
                string   date         = current_date.Year.ToString() + ".";

                if (current_date.Month.ToString().Length == 1)
                {
                    date += "0" + current_date.Month.ToString() + ".";
                }
                else
                {
                    date += current_date.Month.ToString() + ".";
                }

                if (current_date.Day.ToString().Length == 1)
                {
                    date += "0" + current_date.Day.ToString("");
                }
                else
                {
                    date += current_date.Day.ToString();
                }

                if (stream_schedule.Count == 0)
                {
                    ApiInteraction api = new ApiInteraction(this.Assets);

                    var full_schedule = api.GetListOfApiMembers();

                    foreach (var item in full_schedule)
                    {
                        if (item.subGroup != null && item.subGroup.Contains(data.GetGroup()))
                        {
                            stream_schedule.Add(item);
                        }
                        else if (item.stream != null && item.stream.Contains(data.GetGroup()))
                        {
                            stream_schedule.Add(item);
                        }
                    }
                }

                today_schedule_for_list = new List <string>();
                today_schedule          = new List <ApiInteractionMember>();

                foreach (var item in stream_schedule)
                {
                    if (item.date == date)
                    {
                        today_schedule_for_list.Add(item.beginLesson + "-" + item.endLesson + " " + item.discipline + " " + item.auditorium);
                        today_schedule.Add(item);
                    }
                }

                foreach (var item in added_events)
                {
                    if (item.date == date)
                    {
                        today_schedule_for_list.Add(item.beginLesson + " " + item.discipline);
                        today_schedule.Add(item);
                    }
                }

                today_schedule = today_schedule.OrderBy(o => o.beginLesson).ToList();
                today_schedule_for_list.Sort();


                string[] items = today_schedule_for_list.ToArray();

                listView.Adapter = new ArrayAdapter <String>(this, Android.Resource.Layout.SimpleListItem1, items);

                listView.ItemClick += (object senderlist, ListView.ItemClickEventArgs e_list) =>
                {
                    string message = "";

                    if (today_schedule[e_list.Position].auditorium != null)
                    {
                        message += "Auditorium: " + today_schedule[e_list.Position].auditorium;
                    }
                    if (today_schedule[e_list.Position].beginLesson != null)
                    {
                        message += "\n\nBegin Lesson: " + today_schedule[e_list.Position].beginLesson;
                    }
                    if (today_schedule[e_list.Position].endLesson != null)
                    {
                        message += "\n\nEnd Lesson: " + today_schedule[e_list.Position].endLesson;
                    }
                    if (today_schedule[e_list.Position].discipline != null)
                    {
                        message += "\n\nDiscipline: " + today_schedule[e_list.Position].discipline;
                    }
                    if (today_schedule[e_list.Position].lecturer != null)
                    {
                        message += "\n\nLecturer: " + today_schedule[e_list.Position].lecturer;
                    }
                    if (today_schedule[e_list.Position].kindOfWork != null)
                    {
                        message += "\n\nKind Of Work: " + today_schedule[e_list.Position].kindOfWork;
                    }
                    if (today_schedule[e_list.Position].building != null)
                    {
                        message += "\n\nBuilding: " + today_schedule[e_list.Position].building;
                    }
                    if (today_schedule[e_list.Position].dayOfWeekString != null)
                    {
                        message += "\n\nDay Of Week: " + today_schedule[e_list.Position].dayOfWeekString;
                    }
                    if (today_schedule[e_list.Position].group != null)
                    {
                        message += "\n\nGroup: " + today_schedule[e_list.Position].group;
                    }
                    if (today_schedule[e_list.Position].subGroup != null)
                    {
                        message += "\n\nSubgroup: " + today_schedule[e_list.Position].subGroup;
                    }
                    if (today_schedule[e_list.Position].stream != null)
                    {
                        message += "\n\nStream: " + today_schedule[e_list.Position].stream;
                    }

                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.SetTitle("Schedule");
                    builder.SetMessage(message);
                    builder.SetPositiveButton("Ok", (sender1, args1) => {
                        builder.Dispose();
                    });

                    builder.SetNegativeButton("Delete this item", (sender1, args1) => {
                        int index = e_list.Position;
                        //today_schedule.RemoveAt(index);
                        var item_need_to_delete = today_schedule[index];

                        bool isFound = false;
                        int i        = 0;
                        while (!isFound && i < added_events.Count)
                        {
                            if ((added_events[i].discipline == item_need_to_delete.discipline) && (added_events[i].beginLesson == item_need_to_delete.beginLesson) && (added_events[i].date == item_need_to_delete.date))
                            {
                                added_events.RemoveAt(i);

                                isFound = true;
                            }
                            else
                            {
                                i++;
                            }
                        }

                        i       = 0;
                        isFound = false;
                        while (!isFound && i < stream_schedule.Count)
                        {
                            if ((stream_schedule[i].discipline == item_need_to_delete.discipline) && (stream_schedule[i].beginLesson == item_need_to_delete.beginLesson) && (stream_schedule[i].endLesson == item_need_to_delete.endLesson) &&
                                (stream_schedule[i].date == item_need_to_delete.date))
                            {
                                stream_schedule.RemoveAt(i);

                                isFound = true;
                            }
                            else
                            {
                                i++;
                            }
                        }

                        tabSettings.Select();
                        tabSchedule.Select();
                    });

                    builder.Show();
                };

                TextView    textCurrentDay = FindViewById <TextView> (Resource.Id.textViewDate);
                ImageButton btn_prev;
                ImageButton btn_second;

                textCurrentDay.Text = DateTime.Now.AddDays(addedDays).ToString("yyyy-M-d dddd");

                btn_prev   = FindViewById <ImageButton> (Resource.Id.imageButtonPrev);
                btn_second = FindViewById <ImageButton> (Resource.Id.imageButtonSecond);

                btn_prev.Click += delegate {
                    addedDays -= 1;
                    tabSettings.Select();
                    tabSchedule.Select();
                };

                btn_second.Click += delegate {
                    addedDays += 1;
                    tabSettings.Select();
                    tabSchedule.Select();
                };
            };

            ActionBar.AddTab(tabSchedule);

            tabEdit.SetText("Edit Schedule");
            //tab.SetIcon(Resource.Drawable.editsmall);
            tabEdit.TabSelected += (sender, args) => {
                SetContentView(Resource.Layout.Edit);

                Button     btn_ok_add    = FindViewById <Button> (Resource.Id.buttonOkAdd);
                EditText   edit_text_add = FindViewById <EditText> (Resource.Id.editTextAdd);
                TimePicker time_picker   = FindViewById <TimePicker> (Resource.Id.timePicker1);
                time_picker.SetIs24HourView(Java.Lang.Boolean.True);

                btn_ok_add.Click += delegate {
                    var hour    = time_picker.CurrentHour;
                    var minutes = time_picker.CurrentMinute;

                    var text = edit_text_add.Text;

                    string time = "";

                    if (hour.ToString().Length == 1)
                    {
                        time += "0" + hour.ToString();
                    }
                    else
                    {
                        time += hour.ToString();
                    }

                    time += ":";

                    if (minutes.ToString().Length == 1)
                    {
                        time += "0" + minutes.ToString();
                    }
                    else
                    {
                        time += minutes.ToString();
                    }

                    DateTime current_date = DateTime.Now.AddDays(addedDays);
                    string   date         = current_date.Year.ToString() + ".";

                    if (current_date.Month.ToString().Length == 1)
                    {
                        date += "0" + current_date.Month.ToString() + ".";
                    }
                    else
                    {
                        date += current_date.Month.ToString() + ".";
                    }

                    if (current_date.Day.ToString().Length == 1)
                    {
                        date += "0" + current_date.Day.ToString("");
                    }
                    else
                    {
                        date += current_date.Day.ToString();
                    }
                    added_events.Add(new ApiInteractionMember("null", 0, time, "null", date, "null", 0, "null", text, "null", "null", 0, "null", "null", 0, "null", 0, "null", 0));

                    tabSchedule.Select();
                };
            };

            ActionBar.AddTab(tabEdit);

            // This event fires when the ServiceConnection lets the client (our App class) know that
            // the Service is connected. We use this event to start updating the UI with location
            // updates from the Service
            App.Current.LocationServiceConnected += (object sender, ServiceConnectedEventArgs e) => {
                //Log.Debug (logTag, "ServiceConnected Event Raised");
                // notifies us of location changes from the system
                App.Current.LocationService.LocationChanged += HandleLocationChanged;
                //notifies us of user changes to the location provider (ie the user disables or enables GPS)
                App.Current.LocationService.ProviderDisabled += HandleProviderDisabled;
                App.Current.LocationService.ProviderEnabled  += HandleProviderEnabled;
                // notifies us of the changing status of a provider (ie GPS no longer available)
                App.Current.LocationService.StatusChanged += HandleStatusChanged;
            };

            // Start the location service:
            App.StartLocationService();
        }
コード例 #22
0
        private async void TxtView_Click(object sender, EventArgs e)
        {
            var isValid = dataForm.Validate() && dataForm2.Validate();

            if (!isValid)
            {
                return;
            }
            if (!isChecked)
            {
                Toast.MakeText(Context.ApplicationContext, "Accept the terms of use", ToastLength.Short).Show();
            }
            else
            {
                if (!CrossConnectivity.Current.IsConnected)
                {
                    Toast.MakeText(Context.ApplicationContext, "No Internet Connection", ToastLength.Short).Show();
                }
                else
                {
                    dataForm.Commit();
                    dataForm2.Commit();

                    var sfBsyIndicator = new SfBusyIndicator(Context.ApplicationContext);
                    sfBsyIndicator.AnimationType  = AnimationTypes.Ball;
                    sfBsyIndicator.TitlePlacement = TitlePlacement.Top;
                    sfBsyIndicator.TextColor      = Color.Purple;
                    sfBsyIndicator.ViewBoxHeight  = 100;
                    sfBsyIndicator.ViewBoxWidth   = 100;
                    sfBsyIndicator.IsBusy         = true;
                    sfBsyIndicator.SecondaryColor = Color.Purple;
                    sfBsyIndicator.SetBackgroundResource(Color.Transparent);

                    var builder = new AlertDialog.Builder(CrossCurrentActivity.Current.Activity,
                                                          Resource.Style.AlertDialogTheme);
                    var alertDialog = builder.SetView(sfBsyIndicator).Create();
                    alertDialog.SetCanceledOnTouchOutside(false);
                    alertDialog.Show();
                    alertDialog.Window.SetLayout(1000, 300);

                    var phoneNumber = string.Concat(phoneInfo.CountryCode, phoneInfo.PhoneNumber);
                    var httpClient  = new HttpClient();
                    var funcUri     =
                        $"https://e-spafunctions.azurewebsites.net/api/UserExistence?code=FvvkqYX9HQxJsr4AliXfv6jqZ3uttw8wzUNezzKiXHowx4EwUVdqdQ==&phoneNo={phoneNumber}";
                    var response = await httpClient.GetAsync(funcUri);

                    alertDialog.Cancel();


                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        Toast.MakeText(Context.ApplicationContext,
                                       "An Account is already associated with that phoneNumber", ToastLength.Long).Show();
                        var str = await response.Content.ReadAsStringAsync();

                        client = JsonConvert.DeserializeObject <Client>(str);
                    }
                    else
                    {
                        var fragment = new PhoneNumberVerificationFragment();
                        var phInfo   = JsonConvert.SerializeObject(phoneInfo);
                        var usInfo   = JsonConvert.SerializeObject(userInfo);

                        var bundle = new Bundle();
                        bundle.PutString("phoneInfo", phInfo);
                        bundle.PutString("userInfo", usInfo);
                        fragment.Arguments = bundle;


                        var alertDialogBuilder = new AlertDialog.Builder(CrossCurrentActivity.Current.Activity, Resource.Style.AppTheme)
                                                 .SetTitle("Phone Number Verification")
                                                 .SetMessage($"We shall be verifying the phone Number {string.Concat(phoneInfo.CountryCode,phoneInfo.PhoneNumber)} by sending an SMS with a verification Code. Press Yes to continue or No modify the Phone Number")
                                                 .SetNegativeButton("No", (s, arg) => { Dispose(); })
                                                 .SetPositiveButton("Yes", ((s, args) =>
                        {
                            var transaction = FragmentManager.BeginTransaction();
                            transaction.SetCustomAnimations(Resource.Animation.anim_enter, Resource.Animation.anim_exit)
                            .Replace(Resource.Id.authorizationContainer, fragment)
                            .AddToBackStack("RegisterNewUser")
                            .Commit();
                        }))
                                                 .Create();
                        alertDialogBuilder.Window.SetLayout(1000, 450);
                        alertDialogBuilder.Show();
                    }
                }
            }
        }
コード例 #23
0
        void showCompleteDialog()
        {
            //Inflate layout
            View        view    = LayoutInflater.Inflate(Resource.Layout.ReceiveOKDialog, null);
            AlertDialog builder = new AlertDialog.Builder(this).Create();

            builder.SetView(view);
            builder.SetCanceledOnTouchOutside(false);

            Button buttonYesAction = view.FindViewById <Button>(Resource.Id.btnYes);
            Button buttonNoAction  = view.FindViewById <Button>(Resource.Id.btnNo);


            buttonYesAction.Click += delegate
            {
                try
                {
                    //send packages
                    foreach (var item in tableItems)
                    {
                        ModelOrder modelOrder = new ModelOrder
                        {
                            Agent       = SELECTED_AGENT,
                            AgentStr    = SELECTED_AGENTSTR,
                            OrderNumber = item.Heading,
                            PackageQty  = item.PackageQty,
                            ReceivedTS  = DateTime.UtcNow,
                            Status      = (int)StatusTypeEnums.RECEIVED
                        };

                        ReceivePackageModel model = new ReceivePackageModel
                        {
                            ModelOrder = modelOrder,
                            UpdateTS   = false
                        };

                        if (GetConnectionStatus())
                        {
                            var result = _transactionService.ReceivePackage(model);

                            if (!result)
                            {
                                // TBD: If api fails to process a package
                                AddToLocalReceiveTable(model);
                                continue;
                            }
                        }
                        else
                        {
                            // save to local db
                            AddToLocalReceiveTable(model);
                        }
                    }

                    UserSession.SendingAllPendingTransactions();

                    // clear all info
                    ClearScreen();

                    // Reset ListView
                    InitializeListView();

                    // Display Dialog
                    Android.Widget.Toast.MakeText(this, "Transaction Completed!", Android.Widget.ToastLength.Short).Show();

                    builder.Dismiss();

                    Finish();
                }
                catch
                {
                    Android.Widget.Toast.MakeText(this, "Error : Cannot Process Transaction!", Android.Widget.ToastLength.Short).Show();
                }
            };

            buttonNoAction.Click += delegate
            {
                builder.Dismiss();
            };

            builder.Show();
        }
コード例 #24
0
        public void PLC_Connect(string m_SendMessage)
        {
            Socket    m_SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            string    m_RemoteIP     = "192.168.31.31";
            IPAddress m_RemoteAddress;

            while (true)
            {
                if (!IPAddress.TryParse(m_RemoteIP, out m_RemoteAddress))
                {
                    AlertDialog.Builder alert = new AlertDialog.Builder(this);
                    alert.SetTitle("關於IP位置格式");
                    alert.SetMessage("IP位置格式錯誤檢查IP再試試");
                    alert.Show();
                }
                else
                {
                    break;
                }
            }
            IPEndPoint m_IPPoint = new IPEndPoint(m_RemoteAddress, 4999);

            try
            {
                m_SocketClient.Connect(m_IPPoint);
                byte[] m_RecvBuffer = new byte[8192];
                byte[] m_SendBuffer;
                int    m_RecvLen;
                m_SendBuffer = Encoding.Default.GetBytes(m_SendMessage);
                m_SocketClient.Send(m_SendBuffer, m_SendBuffer.Length, SocketFlags.None);
                m_RecvLen = m_SocketClient.Receive(m_RecvBuffer, SocketFlags.None);
                ShowMessage(m_RecvBuffer, m_RecvLen);
                m_SocketClient.Shutdown(SocketShutdown.Both);
                m_SocketClient.Close();
            }
            catch (Exception ex)
            {
                m_SocketClient.Close();
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.SetTitle("錯誤發生請確認PLC連線  " + "異常訊息:" + ex.Message);
                alert.Show();
            }
            /*解碼並顯示伺服器傳回的訊息*/
            void ShowMessage(byte[] buffer, int len)
            {
                REC_PLC = Encoding.Default.GetString(buffer, 0, len);
                //   VoiceLuisApp.Models.PLC_Display_class D10_D19 = REC_PLC;
                PLC_Data_Class = new ObservableCollection <PLC_Display_class>();
                PLC_Data_Class.Add(new PLC_Display_class {
                    PLC_Display = REC_PLC
                });
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                if (REC_PLC == "8300")
                {
                    // Write to PLC
                }
                else
                {
                    LiftFloorTextView.Text = "電梯目前移動從" + REC_PLC.Substring(11, 1) + "樓移動至" + REC_PLC.Substring(7, 1) + "樓";
                }
            }
        }
コード例 #25
0
ファイル: MainActivity.cs プロジェクト: empowerhack/Beacon
        private async void SendMessage()
        {
            if (string.IsNullOrWhiteSpace(phoneNumber))
            {
                ChangePhoneNum(true);
                return;
            }

            TelephonyManager manager = (TelephonyManager)this.GetSystemService(Context.TelephonyService);

            if (manager.PhoneType == PhoneType.None)
            {
                // No SMS capability!
                AlertDialog alert = new AlertDialog.Builder(this)
                                    .SetTitle("Error!")
                                    .SetMessage("You can't send text messages on this device! Familyr works by sending SMS messages.")
                                    .Create();
                alert.Show();

                return;
            }

            if (!connected)
            {
                Toast.MakeText(this, "Waiting for connection to API", ToastLength.Long).Show();
                while (!connected)
                {
                    await Task.Delay(1000);
                }
            }

            try
            {
                Location lastLoc = LocationServices.FusedLocationApi.GetLastLocation(apiClient);

                if (lastLoc != null)
                {
                    double          lat       = lastLoc.Latitude;
                    double          lon       = lastLoc.Longitude;
                    Geocoder        geocoder  = new Geocoder(this, Locale.Default);
                    IList <Address> addresses = await geocoder.GetFromLocationAsync(lat, lon, 1);

                    if (addresses == null || addresses.Count == 0)
                    {
                        Toast.MakeText(this, "No addresses found", ToastLength.Long).Show();
                        return;
                    }
                    Address add = addresses[0];

                    string message = string.Format("{0} has reported their location at {1}, {2}.\n" +
                                                   "Lat: {3}\n" +
                                                   "Long: {4}\n" +
                                                   "http://maps.google.com/maps?q=loc:{3},{4}",
                                                   "Familyr member 1", add.Locality, add.PostalCode, lat, lon);

                    SmsManager.Default.SendTextMessage(phoneNumber, null, message, null, null);

                    Toast.MakeText(this, "Sent!", ToastLength.Long).Show();
                }
                else
                {
                    Toast.MakeText(this, "Failed to get location", ToastLength.Long).Show();
                }
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, "Error: " + ex.Message, ToastLength.Long).Show();
            }
        }
コード例 #26
0
        private async void SaveMapAsync(object sender, OnSaveMapEventArgs e)
        {
            var alertBuilder = new AlertDialog.Builder(this);

            // Get the current map
            var myMap = _myMapView.Map;

            try
            {
                // Show the progress bar so the user knows work is happening
                _progressBar.Visibility = ViewStates.Visible;

                // Get information entered by the user for the new portal item properties
                var title       = e.MapTitle;
                var description = e.MapDescription;
                var tags        = e.Tags;

                // Apply the current extent as the map's initial extent
                myMap.InitialViewpoint = _myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);

                // Export the current map view for the item's thumbnail
                RuntimeImage thumbnailImg = await _myMapView.ExportImageAsync();

                // See if the map has already been saved (has an associated portal item)
                if (myMap.Item == null)
                {
                    // Call a function to save the map as a new portal item
                    await SaveNewMapAsync(myMap, title, description, tags, thumbnailImg);

                    // Report a successful save
                    alertBuilder.SetTitle("Map Saved");
                    alertBuilder.SetMessage("Saved '" + title + "' to ArcGIS Online!");
                    alertBuilder.Show();
                }
                else
                {
                    // This is not the initial save, call SaveAsync to save changes to the existing portal item
                    await myMap.SaveAsync();

                    // Get the file stream from the new thumbnail image
                    Stream imageStream = await thumbnailImg.GetEncodedBufferAsync();

                    // Update the item thumbnail
                    (myMap.Item as PortalItem).SetThumbnailWithImage(imageStream);
                    await myMap.SaveAsync();

                    // Report update was successful
                    alertBuilder.SetTitle("Updates Saved");
                    alertBuilder.SetMessage("Saved changes to '" + myMap.Item.Title + "'");
                    alertBuilder.Show();
                }
            }
            catch (Exception ex)
            {
                // Show the exception message
                alertBuilder.SetTitle("Unable to save map");
                alertBuilder.SetMessage(ex.Message);
                alertBuilder.Show();
            }
            finally
            {
                // Hide the progress bar
                _progressBar.Visibility = ViewStates.Invisible;
            }
        }
コード例 #27
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.CreateAccount);

            var    image1    = FindViewById <ImageView>(Resource.Id.imageView1);
            var    edtUser   = FindViewById <EditText>(Resource.Id.edTxtUserName);
            var    edtPass   = FindViewById <EditText>(Resource.Id.edTxtPassword);
            var    edtConf   = FindViewById <EditText>(Resource.Id.edTxtConfPassword);
            var    btnCreate = FindViewById <Button>(Resource.Id.btnCreateAccount);
            string dbPath    = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "dbUser.db3");

            btnCreate.Click += delegate
            {
                var db    = new SQLiteConnection(dbPath);
                var table = db.Table <LogIn>();

                if (edtUser.Text == "")
                {
                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                    alertDialog.SetTitle("Error");
                    alertDialog.SetMessage("Invalid Username");
                    alertDialog.SetNeutralButton("OK", delegate
                    {
                        alertDialog.Dispose();
                    });
                    alertDialog.Show();
                }
                else if (edtPass.Text == "")
                {
                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                    alertDialog.SetTitle("Error");
                    alertDialog.SetMessage("Invalid Password");
                    alertDialog.SetNeutralButton("OK", delegate
                    {
                        alertDialog.Dispose();
                    });
                    alertDialog.Show();
                }
                else if (edtPass.Text != edtConf.Text)
                {
                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                    alertDialog.SetTitle("Error");
                    alertDialog.SetMessage("Passwords are not the same");
                    alertDialog.SetNeutralButton("OK", delegate
                    {
                        alertDialog.Dispose();
                    });
                    alertDialog.Show();
                }
                else
                {
                    Boolean allow = true;

                    foreach (var item in table)
                    {
                        if (item.UserName == edtUser.Text)
                        {
                            allow = false;
                            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                            alertDialog.SetTitle("Error");
                            alertDialog.SetMessage("Username is already in use");
                            alertDialog.SetNeutralButton("OK", delegate
                            {
                                alertDialog.Dispose();
                            });
                            alertDialog.Show();
                        }
                    }

                    if (allow)
                    {
                        LogIn newLogIn = new LogIn();
                        newLogIn.UserName = edtUser.Text;
                        newLogIn.Password = edtPass.Text;
                        db.Insert(newLogIn);
                        StartActivity(typeof(MainActivity));
                    }
                }
            };
        }
コード例 #28
0
 public void Show()
 {
     _builder.Show();
 }
コード例 #29
0
ファイル: MainActivity.cs プロジェクト: eatage/SQLiteAndroid
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            //注册控件
            EditText txt_writeKey   = FindViewById <EditText>(Resource.Id.txt_WriteKey);
            EditText txt_writeValue = FindViewById <EditText>(Resource.Id.txt_WriteValue);
            EditText txt_ReadKey    = FindViewById <EditText>(Resource.Id.txt_ReadKey);
            Button   btn_Write      = FindViewById <Button>(Resource.Id.btn_Write);
            Button   btn_Read       = FindViewById <Button>(Resource.Id.btn_Read);

            //点击按钮
            btn_Write.Click += (o, e) =>
            {
                if (txt_writeKey.Text == "")
                {
                    Toast.MakeText(this, "请输入要写入的Key", ToastLength.Short).Show();
                    return;
                }
                if (txt_writeValue.Text == "")
                {
                    Toast.MakeText(this, "请输入要写入的Value", ToastLength.Short).Show();
                    return;
                }
                CreateTable();
                int count = 0;
                count = SqliteHelper.ExecuteScalarNum("select count(key) from test where key=@key",
                                                      "@key=" + txt_writeKey.Text);
                if (count > 0)
                {
                    Toast.MakeText(this, "Key:" + txt_writeKey.Text + " 已存在,不允许重复", ToastLength.Short).Show();
                    return;
                }
                count = SqliteHelper.ExecuteNonQuery("insert into test(key,value)values (@key,@value)",
                                                     "@key=" + txt_writeKey.Text,
                                                     "@value=" + txt_writeValue.Text);
                if (count > 0)
                {
                    txt_writeKey.Text   = "";
                    txt_writeValue.Text = "";
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.SetTitle("提示:");
                    builder.SetMessage("写入成功\n");
                    builder.SetPositiveButton("确定", delegate { });
                    builder.SetNegativeButton("取消", delegate { });
                    builder.Show();
                }
                else
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.SetTitle("提示:");
                    builder.SetMessage("写入失败\n" + SqliteHelper.SqlErr);
                    builder.SetPositiveButton("确定", delegate { });
                    builder.SetNegativeButton("取消", delegate { });
                    builder.Show();
                }
            };
            btn_Read.Click += (o, e) =>
            {
                if (txt_ReadKey.Text == "")
                {
                    Toast.MakeText(this, "请输入要读取的Key", ToastLength.Short).Show();
                    return;
                }
                string value = SqliteHelper.ExecuteScalar("select value from test where key=@key",
                                                          "@key=" + txt_ReadKey.Text);
                if (string.IsNullOrEmpty(value))
                {
                    Toast.MakeText(this, "Key:" + txt_ReadKey.Text + " 不存在,清先写入该Key", ToastLength.Short).Show();
                    return;
                }
                txt_ReadKey.Text = "";
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.SetTitle("提示:");
                builder.SetMessage("Key:" + txt_ReadKey.Text + " 对应的value为\n" + value);
                builder.SetPositiveButton("确定", delegate { });
                builder.SetNegativeButton("取消", delegate { });
                builder.Show();
            };
        }
コード例 #30
0
        //#####################################################################
        // ONCREATE METHOD###################
        //#####################################################################

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

            Xamarin.Essentials.Platform.Init(this, bundle);

            var current = Connectivity.NetworkAccess;

            if (current != NetworkAccess.Internet)
            {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                alertDialog.SetTitle("Connexion Internet Requise");
                alertDialog.SetMessage("Votre appareil ne semble pas être connecté à Internet.\n\nVous devez être conecté pour accéder aux articles !");
                alertDialog.SetNeutralButton("OK", delegate
                {
                    alertDialog.Dispose();
                });
                alertDialog.Show();
            }


            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            var contactUsButton    = FindViewById <Button>(Resource.Id.contactUsButton1);
            var fullScreenBUTTON   = FindViewById <Button>(Resource.Id.newButton1);
            var lastArticlesBUTTON = FindViewById <Button>(Resource.Id.lastArticlesButton);
            var helpUsBUTTON       = FindViewById <Button>(Resource.Id.helpUsButton1);

            //Ouverture nouvelle activité : Fullscreenmode
            fullScreenBUTTON.Click += (s, e) =>
            {
                Intent nextActivity = new Intent(this, typeof(FullScreenActivity));
                StartActivity(nextActivity);
            };

            //Ouverture nouvelle activité : Lastarticles
            lastArticlesBUTTON.Click += (s, e) =>
            {
                Intent nextActivity = new Intent(this, typeof(NotifActivity));
                StartActivity(nextActivity);
            };

            helpUsBUTTON.Click += (s, e) =>
            {
                Intent nextActivity = new Intent(this, typeof(HelpUsActivity));
                StartActivity(nextActivity);
            };



            //Message alerte afficher coordonées developpeur
            contactUsButton.Click += ContactUsButtonClick;


            async void ContactUsButtonClick(object sender, EventArgs e)
            {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                alertDialog.SetTitle("Coordonnées du développeur");
                alertDialog.SetMessage("\[email protected]\n\nCette adresse a été copiée dans le presse papier.\nMerci de votre aide !\n\nLa ThomatoTeam :)");
                alertDialog.SetNeutralButton("OK", delegate
                {
                    alertDialog.Dispose();
                });
                alertDialog.Show();
                var hasText = Clipboard.HasText;
                await Clipboard.SetTextAsync("*****@*****.**");
            }

            web_view = FindViewById <WebView>(Resource.Id.webview);
            web_view.Settings.JavaScriptEnabled = true;
            web_view.SetWebViewClient(new HelloWebViewClient());
            web_view.LoadUrl("https://lcdgg.thomascyrix.com/");
        }
コード例 #31
0
        private async Task <bool> StartTest()
        {
            var rig         = test.rig;
            var connections = test.connections.Values;

            var progress = new ProgressDialog(this);

            progress.SetTitle("Please Wait...");
            progress.SetMessage("We are connecting to all of the devices. Please wait.");
            progress.Indeterminate = true;
            progress.SetCancelable(false);

            handler.Post(() => {
                progress.Show();
            });

            Action dismiss = new Action(() => {
                handler.Post(() => {
                    progress.Dismiss();
                });
            });

            // First we will need to connect to the rig
            var start = DateTime.Now;

            rig.Connect();
            while (DateTime.Now - start <= TimeSpan.FromSeconds(30))
            {
                if (rig.isConnected)
                {
                    break;
                }
                else
                {
                    await Task.Delay(TimeSpan.FromMilliseconds(150));
                }
            }

            if (!rig.isConnected)
            {
                handler.Post(() => {
                    var adb = new AlertDialog.Builder(this);
                    adb.SetTitle("Failed to Start Test");
                    adb.SetMessage("Failed to connect to the test rig.");
                    adb.SetNegativeButton("Well, then connect to the rig?!", (sender, e) => {
                    });
                    adb.Show();
                });

                dismiss();
                StopTest();
                return(false);
            }

            var missingConnection = false;

            for (var attempts = 3; attempts >= 2; attempts--)
            {
                // Connect to all of the selected connections.
                foreach (var connection in connections)
                {
                    handler.Post(() => {
                        if (!connection.isConnected)
                        {
                            connection.Connect();
                        }
                    });
                    await Task.Delay(TimeSpan.FromMilliseconds(2000));
                }

                start = DateTime.Now;
                while (DateTime.Now - start <= TimeSpan.FromSeconds(20))
                {
                    missingConnection = false;
                    foreach (var connection in connections)
                    {
                        if (!connection.isConnected)
                        {
                            missingConnection = true;
                            break;
                        }
                    }

                    if (!missingConnection)
                    {
                        break;
                    }
                    else
                    {
                        await Task.Delay(150);
                    }
                }

                // Check if we need another try
                bool needsAnotherTry = false;
                foreach (var connection in connections)
                {
                    if (!connection.isConnected)
                    {
                        connection.Disconnect();
                        needsAnotherTry = true;
                    }
                }

                if (needsAnotherTry)
                {
                    continue;
                }
            }

            dismiss();

            if (!rig.isConnected)
            {
                missingConnection = true;
            }
            else
            {
                foreach (var connection in connections)
                {
                    if (!connection.isConnected)
                    {
                        missingConnection = true;
                        break;
                    }
                }
            }

            if (missingConnection)
            {
                var sb = new StringBuilder();
                sb.Append("Failed to connect to the following devices:\n");
                if (!rig.isConnected)
                {
                    sb.Append("TestRig, ");
                }
                foreach (var connection in connections)
                {
                    if (!connection.isConnected)
                    {
                        sb.Append(connection.serialNumber).Append(", ");
                    }
                }

                var adb = new AlertDialog.Builder(this);
                adb.SetTitle("Failed to Start Test");
                adb.SetMessage(sb.ToString());
                adb.SetCancelable(false);
                adb.SetNegativeButton("Cancel", (sender, e) => {
                });
                adb.Show();

                StopTest();
                return(false);
            }
            else
            {
                test.StartTest();
                return(true);
            }
        }
コード例 #32
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Configuraciones);

            ISharedPreferences       prefs      = Application.Context.GetSharedPreferences("Settings", FileCreationMode.Private);
            ISharedPreferencesEditor prefEditor = prefs.Edit();

            botonseleccionarcarpeta = FindViewById <Button>(Resource.Id.imageView1);
            localizacion            = FindViewById <TextView>(Resource.Id.textView3);
            //   botonguardar = FindViewById<ImageView>(Resource.Id.imageView2);
            var colormuestra = FindViewById <ImageView>(Resource.Id.imageView3);

            colormuestra.SetBackgroundColor(Color.ParseColor(SettingsHelper.GetSetting("color")));
            color            = SettingsHelper.GetSetting("color");
            reprodautomatica = SettingsHelper.GetSetting("automatica");
            var ll1             = FindViewById <LinearLayout>(Resource.Id.linearLayout3);
            var ll2             = FindViewById <LinearLayout>(Resource.Id.linearLayout4);
            var ll3             = FindViewById <LinearLayout>(Resource.Id.linearLayout5);
            var ll4             = FindViewById <LinearLayout>(Resource.Id.linearLayout7);
            var ll5             = FindViewById <LinearLayout>(Resource.Id.linearLayout23);
            var fondo           = FindViewById <ImageView>(Resource.Id.fondo1);
            var toggle1         = FindViewById <Android.Support.V7.Widget.SwitchCompat>(Resource.Id.toggleButton1);
            var toggle2         = FindViewById <Android.Support.V7.Widget.SwitchCompat>(Resource.Id.toggleButton2);
            var automatica      = FindViewById <Android.Support.V7.Widget.SwitchCompat>(Resource.Id.automatico);
            var botonclearcache = FindViewById <LinearLayout>(Resource.Id.linearLayout8);

            calidades = FindViewById <Spinner>(Resource.Id.spinner1);
            var action = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.my_toolbar);

            //////////////////////////////////////coloreselector mappings

#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
            dialogoprogreso = new ProgressDialog(this);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
            ///////////////////////////////////////////////////////////

            ////////////////////////////////////////////////////////////////
            ///
            if (reprodautomatica == "si")
            {
                automatica.Checked = true;
            }
            else
            {
                automatica.Checked = false;
            }


            SetSupportActionBar(action);
            SupportActionBar.Title = "Preferencias";
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);

            var adapter = new  ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem);
            adapter.AddAll(new string[] { "Audio", "360p", "720p" }.ToList());
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            calidades.Adapter = adapter;

            color   = SettingsHelper.GetSetting("color");
            calidad = int.Parse(SettingsHelper.GetSetting("video"));
            switch (calidad)
            {
            case -1:
                calidades.SetSelection(0);
                break;

            case 360:
                calidades.SetSelection(1);
                break;

            case 720:
                calidades.SetSelection(2);
                break;
            }

            if (SettingsHelper.HasKey("abrirserver"))
            {
                abrirserver = SettingsHelper.GetSetting("abrirserver");
            }
            if (abrirserver == "no")
            {
                toggle2.Checked = false;
            }
            else
            {
                toggle2.Checked = true;
            }


            if (SettingsHelper.HasKey("ordenalfabeto"))
            {
                ordenalfabeto = SettingsHelper.GetSetting("ordenalfabeto");

                if (ordenalfabeto == "si")
                {
                    toggle1.Checked = true;
                }
                else
                {
                    toggle1.Checked = false;
                }
            }

            if (SettingsHelper.HasKey("rutadescarga"))
            {
                klk = prefs.GetString("rutadescarga", null);
            }
            else
            {
                if (Directory.Exists(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads"))
                {
                    klk = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads";
                    prefEditor.PutString("rutadescarga", klk);
                    prefEditor.Commit();
                }
                else
                {
                    Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads");
                    klk = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads";
                    prefEditor.PutString("rutadescarga", klk);
                    prefEditor.Commit();
                }
            }

            localizacion.Text = klk;

            fondo.SetImageBitmap(CreateBlurredImageoffline(this, 20, 0));
            ////////////////////////////////clicks////////////////////////////

            calidades.ItemSelected += (axx, ssd) => {
                switch (ssd.Position)
                {
                case 0:
                    calidad = -1;
                    break;

                case 1:
                    calidad = 360;
                    break;

                case 2:
                    calidad = 720;
                    break;
                }
            };
            automatica.Click += delegate
            {
                if (automatica.Checked)
                {
                    reprodautomatica = "si";
                    Toast.MakeText(this, "Si no hay mas elementos en cola se reproducira el primer elemento de las sugerencias", ToastLength.Long).Show();
                }
                else
                {
                    reprodautomatica = "no";
                    Toast.MakeText(this, "Si no hay mas elementos en cola no se ejecutara ninguna accion", ToastLength.Long).Show();
                }
            };
            toggle2.Click += delegate
            {
                if (toggle2.Checked)
                {
                    new Thread(() =>
                    {
                        if (PlaylistsHelper.HasMediaElements)
                        {
                            if (File.Exists(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/.gr3cache/version.gr3v"))
                            {
                                abrirserver = "si";

                                StartService(new Intent(this, typeof(serviciostreaming)));
                            }
                            else

                            {
                                AlertDialog dialogo = null;
                                RunOnUiThread(() => {
                                    var progresox           = new ProgressBar(this);
                                    progresox.Indeterminate = true;

                                    dialogo = new AlertDialog.Builder(this)
                                              .SetTitle("Buscando actualizaciones")
                                              .SetMessage("Por favor espere...")
                                              .SetCancelable(false)
                                              .SetView(progresox)
                                              .Show();
                                });
                                if (CheckInternetConnection())
                                {
                                    abrirserver        = "si";
                                    AlertDialog alerta = null;
                                    RunOnUiThread(() =>
                                    {
                                        dialogo.Dismiss();
                                        var progreso           = new ProgressBar(this);
                                        progreso.Indeterminate = true;

                                        alerta = new AlertDialog.Builder(this)
                                                 .SetTitle("Descargando archivos necesarios")
                                                 .SetMessage("Por favor espere...")
                                                 .SetCancelable(false)
                                                 .SetView(progreso)
                                                 .Show();
                                    });
                                    new Thread(() =>
                                    {
                                        WebClient cliente = new WebClient();
                                        var version       = cliente.DownloadString("https://raw.githubusercontent.com/Gr3gorywolf/Multitube.android/master/Updates/version.gr3v");
                                        using (var file = File.CreateText(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/.gr3cache/version.gr3v")) {
                                            file.Write(version);
                                            file.Close();
                                        }
                                        MultitubeWebHelper.UpdateMultitubeWeb(version);
                                        RunOnUiThread(() =>
                                        {
                                            alerta.Dismiss();
                                            StartService(new Intent(this, typeof(serviciostreaming)));
                                            new AlertDialog.Builder(this)
                                            .SetTitle("Informacion")
                                            .SetMessage("El servidor de streaming le permitirara reproducir su contenido previamente descargado desde cualquier navegador de cualquier dispositivo conectado a su misma red. Puede consultar el estado de este en la barra de notificaciones")
                                            .SetPositiveButton("Entendido!", (aa, fff) => { })
                                            .Create()
                                            .Show();
                                        });
                                    }).Start();
                                }
                                else
                                {
                                    RunOnUiThread(() =>
                                    {
                                        dialogo.Dismiss();
                                        Toast.MakeText(this, "Debe tener una conexion a internet para abrir el servicio por primera vez", ToastLength.Long).Show();
                                        toggle2.Checked = false;
                                    });
                                }
                            }
                        }
                        else
                        {
                            RunOnUiThread(() =>
                            {
                                toggle2.Checked = false;
                                Toast.MakeText(this, "Debe tener almenos 1 elemento descargado", ToastLength.Long).Show();
                            });
                        }
                    }).Start();
                }
                else
                {
                    if (serviciostreaming.gettearinstancia() != null)
                    {
                        StopService(new Intent(this, typeof(serviciostreaming)));
                    }
                    toggle2.Checked = false;
                    abrirserver     = "no";
                }
            };
            botonclearcache.Click += delegate
            {
                AlertDialog.Builder ad = new AlertDialog.Builder(this);
                ad.SetCancelable(false);
                ad.SetTitle("Advertencia");
                ad.SetIcon(Resource.Drawable.alert);
                ad.SetMessage("Limpiar el cache puede provocar cierta realentizacion a la hora de entrar al reproductor offline y tambien volvera a descargar los datos por lo cual necesitara internet ¿¿quiere borrar cache??");
                ad.SetNegativeButton("No", no);
                ad.SetPositiveButton("Si", si);
                ad.Create();
                ad.Show();
            };
            toggle1.Click += delegate
            {
                if (toggle1.Checked == true)
                {
                    ordenalfabeto = "si";
                    Toast.MakeText(this, "Los elementos se organizaran alfabeticamente", ToastLength.Long).Show();
                }
                else
                {
                    ordenalfabeto = "no";
                    Toast.MakeText(this, "Los elementos se por fecha de descarga", ToastLength.Long).Show();
                }
            };
            botonseleccionarcarpeta.Click += async delegate
            {
                SimpleFileDialog sfd = new SimpleFileDialog(this, SimpleFileDialog.FileSelectionMode.FolderChooseRoot);
                klk = await sfd.GetFileOrDirectoryAsync(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath);

                if (probarpath(klk))
                {
                    pathvalido = true;

                    localizacion.Text = klk;
                }
                else
                {
                    Toast.MakeText(this, "Ruta invalida seleccione otra", ToastLength.Short).Show();
                    klk        = localizacion.Text;
                    pathvalido = false;
                }
            };
        }
        public void enemyMove()
        {
            etimer          = new System.Timers.Timer();
            etimer.Interval = 24 - (level * 4);
            etimer.Elapsed += (sender, e) =>
            {
                RunOnUiThread(() =>
                {
                    ImageView enemy  = FindViewById <ImageView>(Resource.Id.mini);
                    ImageView rocket = FindViewById <ImageView>(Resource.Id.rocket);

                    var metrics = Resources.DisplayMetrics;


                    int width  = metrics.WidthPixels - enemy.Width;
                    int height = metrics.HeightPixels - (enemy.Width * 2);

                    if (bx > width)
                    {
                        dx = -1;
                    }
                    if (bx < 20)
                    {
                        dx = 1;
                    }


                    if (by > height)
                    {
                        dy = -1;
                    }
                    if (by < 0)
                    {
                        dy = 1;
                    }



                    if ((rocket.GetY() + (rocket.Height / 2) <= by + enemy.Height || (rocket.GetY() + (rocket.Height / 2) <= by) && by >= rocket.GetY()) && rocket.GetX() + rocket.Width >= bx)
                    {
                        ProgressBar userLife = FindViewById <ProgressBar>(Resource.Id.user_life);
                        userLife.Progress   -= 20;


                        rocket.Alpha = 0;
                        rocket.Animate()
                        .SetDuration(5000)
                        .Alpha(10);


                        MediaPlayer player1;
                        player1 = MediaPlayer.Create(this, Resource.Raw.blast);
                        player1.Start();
                        player1.SetVolume(SoundSetup.sound_level, SoundSetup.sound_level);


                        by = 0;
                        bx = width;

                        if (userLife.Progress == 0)
                        {
                            etimer.Close();
                            AlertDialog.Builder alert = new AlertDialog.Builder(this);
                            alert.SetTitle("Game Over");
                            alert.SetMessage("Unfortunately enemy has hit your rocket.");
                            alert.SetPositiveButton("Continue", (senderAlert, args) => {
                                Intent activity2 = new Intent(this, typeof(GameOver));
                                string score     = FindViewById <TextView>(Resource.Id.score).Text;
                                activity2.PutExtra("score", score);
                                this.StartActivity(activity2);
                                this.Finish();
                            });

                            alert.Show();
                        }
                    }

                    bx = bx + dx;
                    enemy.SetX(bx);

                    by = by + dy;
                    enemy.SetY(by);
                });
            };
            etimer.Enabled = true;
        }