public void OnSharedPreferenceChanged (ISharedPreferences sharedPreferences, string key)
		{
			Console.WriteLine ("Preference Changed: " + key);

			switch (key) {
			case "prefshowxamarin":
				settings.ShowXamarinLogo = sharedPreferences.GetBoolean (key, true);
				break;
			case "pref24hourclock":
				settings.Use24Clock = sharedPreferences.GetBoolean (key, false);
				break;
			case "prefshowdayofweek":
				settings.ShowDayOfWeek = sharedPreferences.GetBoolean (key, true);
				break;
			case "prefshowdate":
				settings.ShowDate = sharedPreferences.GetBoolean (key, true);
				break;
			}

			settings.Save ();
			Console.WriteLine ("Settings> " + settings);

			var evt = OnSettingsChanged;
			if (evt != null)
				evt (settings);
		}
 public static AppPreferences Create(ISharedPreferences prefs)
 {
     return new AndroidAppPreferences(prefs)
     {
         FirtsTimeRunning = prefs.GetBoolean(AppPreferences.FirstTimeKey, true),
         Ip = prefs.GetString(AppPreferences.IpKey, ""),
         Port = prefs.GetInt(AppPreferences.PortKey, 0),
         UseSounds = prefs.GetBoolean(AppPreferences.UseSoundsKey, true),
         UseCache = prefs.GetBoolean(AppPreferences.UseCacheKey, true)
     };
 }
Example #3
0
        public void OnSharedPreferenceChanged(ISharedPreferences sharedPreferences, string key)
        {
            string value = string.Empty;

            if (key != "clearCache" && key != "anonymousAccess")
            {
                Preference preference = (Preference)FindPreference(key);

                value = sharedPreferences.GetString(key, string.Empty);

                FillSummary(key, value);

                if ((key == "user" || key == "password" || key == "url") && !sharedPreferences.GetBoolean("clearCache", true))
                {
                    ISharedPreferencesEditor editor = sharedPreferences.Edit();
                    editor.PutBoolean("clearCache", true);
                    editor.Commit();

                    Toast.MakeText(this, D.NEED_TO_REBOOT_FULL, ToastLength.Long).Show();
                }

                if (key == "application")
                {
                    Toast.MakeText(this, D.NEED_TO_REBOOT, ToastLength.Long).Show();
                }
            }
            else
            {
                if (key == "anonymousAccess")
                {
                    string user = "";
                    string password = "";
                    if (sharedPreferences.GetBoolean("anonymousAccess", false))
                    {
                        user = Settings.AnonymousUserName;
                        password = Settings.AnonymousPassword;
                    }
                    ISharedPreferencesEditor editor = sharedPreferences.Edit();
                    editor.PutString("user", user);
                    editor.PutString("password", password);
                    editor.Commit();
                }

                Toast.MakeText(this, D.NEED_TO_REBOOT_FULL, ToastLength.Long).Show();
            }

            BitBrowserApp.Current.SyncSettings(true);
        }
Example #4
0
        public static void Init()
        {
            try
            {
                SharedData   = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
                LastPosition = Application.Context.GetSharedPreferences("last_position", FileCreationMode.Private);
                InAppReview  = Application.Context.GetSharedPreferences("In_App_Review", FileCreationMode.Private);

                string getValue = SharedData.GetString("Night_Mode_key", string.Empty);
                ApplyTheme(getValue);

                var cdv = InitFloating.CanDrawOverlays(Application.Context);
                if (cdv)
                {
                    UserDetails.ChatHead = SharedData.GetBoolean("chatheads_key", cdv);
                }

                PostService.ActionPost  = Application.Context.PackageName + ".action.ACTION_POST";
                PostService.ActionStory = Application.Context.PackageName + ".action.ACTION_STORY";

                UserDetails.SoundControl = SharedData.GetBoolean("checkBox_PlaySound_key", true);
                UserDetails.OnlineUsers  = SharedData?.GetBoolean("notifications_key", true) ?? true;
            }
            catch (Exception e)
            {
                Methods.DisplayReportResultTrack(e);
            }
        }
Example #5
0
        public Settings(ISharedPreferences preferences, string systemLanguage, InfobaseManager.Infobase infobase)
        {
            _preferences = preferences;
            Language = systemLanguage;

            _name = infobase.Name;

            BaseUrl = infobase.BaseUrl;
            ApplicationString = infobase.ApplicationString;

            FtpPort = infobase.FtpPort;

            string lastUrl = _preferences.GetString("url", string.Empty);
            if (BaseUrl == lastUrl)
            {
                UserName = _preferences.GetString("user", infobase.UserName);
                Password = _preferences.GetString("password", infobase.Password);
            }
            else
            {
                UserName = infobase.UserName;
                Password = infobase.Password;
            }

            ClearCacheOnStart = infobase.IsActive && _preferences.GetBoolean("clearCache", ForceClearCache);

            infobase.IsActive = true;
            infobase.IsAutorun = true;

            WriteSettings();
        }
Example #6
0
        public void OnSharedPreferenceChanged(ISharedPreferences sharedPreferences, string key)
        {
            if (key != "clearCache" && key != "anonymousAccess")
            {
                string value = sharedPreferences.GetString(key, string.Empty);

                FillSummary(key, value);

                if ((key == "user" || key == "password" || key == "url") && !sharedPreferences.GetBoolean("clearCache", true))
                {
                    ISharedPreferencesEditor editor = sharedPreferences.Edit();
                    editor.PutBoolean("clearCache", true);
                    editor.Commit();

                    MakeToast(D.NEED_TO_REBOOT_FULL);
                }

                if (key == "application")
                    MakeToast(D.NEED_TO_REBOOT);
            }
            else
            {
                MakeToast(D.NEED_TO_REBOOT_FULL);
            }

            BitBrowserApp.Current.SyncSettings();
        }
		protected override void OnCreate (Bundle savedInstanceState)
		{
			base.OnCreate (savedInstanceState);
			SetContentView(Resource.Layout.main_activity);

			mAddGeofencesButton = FindViewById<Button>(Resource.Id.add_geofences_button);
			mRemoveGeofencesButton = FindViewById<Button>(Resource.Id.remove_geofences_button);

			mAddGeofencesButton.Click += AddGeofencesButtonHandler;
			mRemoveGeofencesButton.Click += RemoveGeofencesButtonHandler;

			mGeofenceList = new List<IGeofence>();

			mGeofencePendingIntent = null;

			mSharedPreferences = GetSharedPreferences(Constants.SHARED_PREFERENCES_NAME,
				FileCreationMode.Private);

			mGeofencesAdded = mSharedPreferences.GetBoolean(Constants.GEOFENCES_ADDED_KEY, false);
			SetButtonsEnabledState();

			PopulateGeofenceList();

			BuildGoogleApiClient();
		}
Example #8
0
        public override void OnCreate()
        {
            base.OnCreate();

            Instance = this;

            // Load preferences
            Preferences = GetSharedPreferences(SettingsFilename, FileCreationMode.Private);
            // Default offline mode
            D3Context.Instance.FetchMode = (Preferences.GetBoolean(SettingsOnlinemode, false) ? FetchMode.Online : FetchMode.OnlineIfMissing);

            // Checks if some migration operations are needed
            var upToDateVersion = Preferences.GetInt(UpToDateVersion, 1);
            if (upToDateVersion < 20)
            {
                new MigrationTo20().DoMigration();
            }

            // Always start D3Api with cache available
            var dataProvider = new CacheableDataProvider(new HttpRequestDataProvider())
            {
                FetchMode = D3Context.Instance.FetchMode
            };
            D3Api.DataProvider = dataProvider;

            // Set english locale by default
            D3Api.Locale = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
        }
 internal OtherSettings(ISharedPreferences sharedPrefs)
 {
     ConnectTimeout = int.Parse(sharedPrefs.GetString("pref_timeout_connect", "10000"));
     ConnectCheckInterval = int.Parse(sharedPrefs.GetString("pref_interval_check_connect", "200"));
     ToastLevel = (ToastLevel)int.Parse(sharedPrefs.GetString("pref_toasts_level", "2"));
     IgnoreSslCertErrors = sharedPrefs.GetBoolean("pref_ignore_ssl_errors", true);
     StartUrl = sharedPrefs.GetString("pref_start_url", null);
 }
Example #10
0
        protected override void OnHandleIntent(Intent intent)
        {
            lastIntent = intent;
            Bundle extras = intent.Extras;
            GoogleCloudMessaging gcm = GoogleCloudMessaging.GetInstance(this);
            string messageType = gcm.GetMessageType(intent);


            if(!extras.IsEmpty)
            {
                userPrefs = PreferenceManager.GetDefaultSharedPreferences(this);

                if(GoogleCloudMessaging.MessageTypeSendError.Equals(messageType))
                {
                    AndroidUtils.SendNotification("Speeching Error", "Error while sending message: " + extras.ToString(), typeof(MainActivity), this);
                }
                else if(GoogleCloudMessaging.MessageTypeDeleted.Equals(messageType))
                {
                    AndroidUtils.SendNotification("Speeching Messages", "Deleted messages on the server", typeof(MainActivity), this);
                }
                else if(GoogleCloudMessaging.MessageTypeMessage.Equals(messageType))
                {
                    string notifType = extras.GetString("notifType");
                    lastType = notifType;
                    PrepClient();

                    // Choose what to do depending on the message type
                    switch (notifType)
                    {
                        case "notification" :
                            if (userPrefs.GetBoolean("prefNotifMessage", true))
                            {
                                // The user wants to receive notifications
                                AndroidUtils.SendNotification(extras.GetString("title"), extras.GetString("message"), typeof(LoginActivity), this);
                            }
                            break;
                        case "locationReminder" :
                            if (userPrefs.GetBoolean("prefNotifMessage", true))
                            {
                                // The user wants to receive notifications
                                ShowReminder();
                            }
                            break;
                        case "newFences" :
                            if (userPrefs.GetBoolean("prefNotifGeofence", true))
                            {
                                // The user wants to have geofences enabled
                                BuildFences(extras.GetString("fences"));
                            }
                            break;
                        case "newActivities" :
                            FetchNewContent();
                            break;
                    }
                   
                }
            }
        }
        public void OnSharedPreferenceChanged(ISharedPreferences sharedPreferences, string key)
        {
            switch (key)
            {
                case PreferenceKeys.Timeout:
                    Runner.Instance.Options.Timeout = sharedPreferences.GetInt(key, Runner.Instance.Options.Timeout);
                    break;
                case PreferenceKeys.SaveNamespaces:
                    if (!sharedPreferences.GetBoolean(key, false))
                        resetSavedNamespaces();

                    break;
                case PreferenceKeys.MultiLineEditing:
                    CSharpToGoApplication.Options.MultiLineEditing = sharedPreferences.GetBoolean(key, CSharpToGoApplication.Options.MultiLineEditing);

                    break;
                case PreferenceKeys.DoubleEnter:
                    CSharpToGoApplication.Options.DoubleEnterToExecute = sharedPreferences.GetBoolean(key, CSharpToGoApplication.Options.DoubleEnterToExecute);

                    break;
            }
        }
Example #12
0
            void DrawFrame()
            {
                ISurfaceHolder holder = SurfaceHolder;
                Canvas         c      = null;

                try
                {
                    c = holder.LockCanvas();
                    if (c != null)
                    {
                        DrawIMG(c);
                        if (Settings.GetBoolean("show_touch", true) == true)
                        {
                            if (touch_point.X >= 0 && touch_point.Y >= 0)
                            {
                                var paint = new Paint();
                                paint.SetStyle(Paint.Style.Stroke);
                                paint.AntiAlias   = true;
                                paint.StrokeWidth = 2;
                                paint.Color       = Color.White;
                                paint.StrokeCap   = Paint.Cap.Round;
                                c.DrawCircle(touch_point.X, touch_point.Y, 80, paint);
                            }
                        }
                    }
                }
                finally
                {
                    if (c != null)
                    {
                        holder.UnlockCanvasAndPost(c);
                    }
                }
                mHandler.RemoveCallbacks(DrawIMGAction);
                if (is_visible)
                {
                    mHandler.PostDelayed(DrawIMGAction, 1000 / 20);
                }
            }
Example #13
0
        protected override void OnResume()
        {
            base.OnResume();

            string homePageUrl   = _preferences.GetString("home_url", "http://10.0.2.2");
            bool   soundsEnabled = _preferences.GetBoolean("sounds", false);
            var    builder       = new StringBuilder();

            builder.AppendLine("Home Page: " + homePageUrl);
            builder.AppendLine("Sounds enabled: " + soundsEnabled);

            _preferenceData.Text = builder.ToString();
        }
Example #14
0
 /// <summary>
 /// inits the views in the main screen and loads the info from the previous runs
 /// </summary>
 private void InitViews()
 {
     llMain      = FindViewById <LinearLayout>(Resource.Id.llMain);
     btnStart    = FindViewById <Button>(Resource.Id.btnStart);
     tvLastScore = FindViewById <TextView>(Resource.Id.tvLastScore);
     tvMaxScore  = FindViewById <TextView>(Resource.Id.tvMaxScore);
     btnName     = FindViewById <Button>(Resource.Id.btnName);
     btnName.SetOnClickListener(this);
     btnStart.SetOnClickListener(this);
     score = new Score();
     llMain.SetBackgroundColor(background);
     score.SetInfo(FileManager.Instance.LoadInfo(this));
     SetScoreInfo();
     AudioManager.IsSoundMuted = sp.GetBoolean(Constants.SOUND, false);
     AudioManager.IsMusicMuted = sp.GetBoolean(Constants.MUSIC, false);
     lastBallChecked           = Size.Medium;
     lastBrickChecked          = Size.Medium;
     lastDifficultyChecked     = Difficulty.Easy;
     SetSizes();
     SetDifficulty();
     GetInfoFromFirestore();
 }
        private void getHistroy()
        {
            bool vFirstRun = prefs.GetBoolean("Notification", false);

            if (vFirstRun)
            {
                toggleNotification.Checked = true;
            }
            else
            {
                toggleNotification.Checked = false;
            }
        }
        public int GetCurrentSortOrderIndex()
        {
            String sortKeyOld = _context.GetString(Resource.String.sort_key_old);
            String sortKey    = _context.GetString(Resource.String.sort_key);

            int sortId = _prefs.GetInt(sortKey, -1);

            if (sortId == -1)
            {
                sortId = _prefs.GetBoolean(sortKeyOld, true) ? 1 : 0;
            }
            return(sortId);
        }
Example #17
0
 public override void OnReceive(Context context, Intent intent)
 {
     if (intent.Action.Equals(Intent.ActionBootCompleted))
     {
         prefs = PreferenceManager.GetDefaultSharedPreferences(context);
         if (prefs.GetBoolean("Notification", false))
         {
             var serviceIntent = new Intent(context, typeof(BatteryService));
             serviceIntent.AddFlags(ActivityFlags.NewTask);
             context.StartForegroundService(serviceIntent);
         }
     }
 }
Example #18
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.activity_main);
            currentContext = this;

            InitView();
            InitViewPager();

            try
            {
                Android.Preferences.PreferenceManager.SetDefaultValues(this, Resource.Xml.preferences_settings, false);
            }
            catch (System.Exception ex)
            { }

            ISharedPreferences sharedPreferences = GetSharedPreferences("app", FileCreationMode.Private);

            if (isShowPageStart)
            {
                relative_main.Visibility = ViewStates.Visible;
                Glide.With(this).Load(Resource.Drawable.ic_launcher_big).Into(img_page_start);
                if (sharedPreferences.GetBoolean("isFirst", true))
                {
                    mHandler.SendEmptyMessageDelayed(MESSAGE_SHOW_START_PAGE, 2000);
                }
                else
                {
                    mHandler.SendEmptyMessageDelayed(MESSAGE_SHOW_START_PAGE, 1000);
                }
                isShowPageStart = false;
            }

            if (sharedPreferences.GetBoolean("isFirst", true))
            {
                mHandler.SendEmptyMessageDelayed(MESSAGE_SHOW_DRAWER_LAYOUT, 2500);
            }
        }
Example #19
0
 private void CheckIsAdmin()
 {
     _preferences = PreferenceManager.GetDefaultSharedPreferences(this);
     IsAdmin      = _preferences.GetBoolean(AppConstant.PrefIsAdmin, false);
     if (IsAdmin)
     {
         ReplaceToStudentList();
     }
     else
     {
         ReplaceToStudentDetails();
     }
 }
Example #20
0
        async void generarCodigo(object sender, EventArgs e)
        {
            ISharedPreferences preferences = PreferenceManager.GetDefaultSharedPreferences(this);
            string             myValue     = "";

            if (preferences.GetBoolean("is_login", false))
            {
                myValue = preferences.GetString("token", "");
                PedidoPost  pedido  = new PedidoPost();
                PedidoModel pedido2 = new PedidoModel();
                pedido.idUsuario = preferences.GetString("name", "");
                pedido.APIKey    = myValue;
                pedido.total     = tota;

                string baseurl = "http://pushstart.azurewebsites.net/api/ApiPedido";
                var    Client  = new HttpClient();
                Client.MaxResponseContentBufferSize = 256000;
                var           uri      = new Uri(baseurl);
                var           json     = JsonConvert.SerializeObject(pedido);
                StringContent content  = new StringContent(json, Encoding.UTF8, "application/json");
                var           response = Client.PostAsync(uri, content).Result;

                if (response.IsSuccessStatusCode)
                {
                    var content2 = await response.Content.ReadAsStringAsync();

                    var items = JsonConvert.DeserializeObject <PedidoModel>(content2);
                    Toast.MakeText(this, "Exito", ToastLength.Short).Show();
                    Intent esIntento = new Intent(this, typeof(detalleYaPa));
                    Bundle esPaquete = new Bundle();
                    esPaquete.PutString("cuenta", items.cuenta);
                    esPaquete.PutString("dinero", items.total.ToString());
                    esPaquete.PutString("idPedido", items.idUsuario.ToString());
                    esIntento.PutExtra("bundle", esPaquete);

                    //Toast.MakeText(this, items.cuenta, ToastLength.Long).Show();
                    StartActivity(esIntento);
                }
                else
                {
                    Toast.MakeText(this, "Algo ha salido mal, lo sentimos. Intente más tarde", ToastLength.Short).Show();
                }
            }
            else
            {
                Toast.MakeText(this, "No ha iniciado sesión", ToastLength.Long).Show();
                myValue = preferences.GetString("NotToken", "");
                Intent intento = new Intent(this, typeof(login2));
                StartActivity(intento);
            }
        }
Example #21
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            //Check if user has a username
            prefs = PreferenceManager.GetDefaultSharedPreferences(this);
            if (!prefs.GetBoolean("first_time_setup", false))
            {
                var PreMainActivity = new Intent(this, typeof(PreMainActivity));
                this.StartActivity(PreMainActivity);
            }

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

            //baby picture
            UpdateBabyImage();


            //4 Menu buttons
            runButton    = FindViewById <ImageButton>(Resource.Id.runButton);
            adviseButton = FindViewById <ImageButton>(Resource.Id.adviseButton);
            storeButton  = FindViewById <ImageButton>(Resource.Id.storeButton);

            runButton.Click    += OpenRunMenu;
            adviseButton.Click += OpenAdviseMenu;
            storeButton.Click  += OpenStoreMenu;

            //ToolBar
            var toolbar = FindViewById <Toolbar>(Resource.Id.toolbar);

            SetActionBar(toolbar);
            ActionBar.Title = "PregApp";

            //Username
            usernameText      = FindViewById <TextView>(Resource.Id.usernameText);
            usernameText.Text = prefs.GetString("username", "username");

            //score
            scoreText = FindViewById <TextView>(Resource.Id.scoreText);

            //steps
            steps = FindViewById <TextView>(Resource.Id.stepsText);
            km    = FindViewById <TextView>(Resource.Id.kmText);

            steps.Click += AddSteps;

            //Start service
            Intent backgroundIntent = new Intent(this, typeof(BackgroundService));

            StartService(backgroundIntent);
        }
Example #22
0
        //todo fix this
        public TPrimitive Get <TPrimitive>(string name) where TPrimitive : struct
        {
            TPrimitive value = default(TPrimitive);
            Type       type  = typeof(TPrimitive);

#if ANDROID
            if (type == typeof(int))
            {
                value = _preferences.GetInt(name, 0).Cast <TPrimitive>();
            }
            else if (type == typeof(bool))
            {
                value = _preferences.GetBoolean(name, true).Cast <TPrimitive>();
            }
            else if (type == typeof(float))
            {
                value = _preferences.GetFloat(name, 0).Cast <TPrimitive>();
            }
            else if (type == typeof(long))
            {
                value = _preferences.GetLong(name, 0).Cast <TPrimitive>();
            }
            else
            {
                throw new NotImplementedException("");
            }
#elif iOS
            if (type == typeof(int))
            {
                value = MonoTouch.Foundation.NSUserDefaults.StandardUserDefaults.IntForKey(name).Cast <TPrimitive>();
            }
            else if (type == typeof(bool))
            {
                value = MonoTouch.Foundation.NSUserDefaults.StandardUserDefaults.BoolForKey(name).Cast <TPrimitive>();
            }
            else if (type == typeof(float))
            {
                value = MonoTouch.Foundation.NSUserDefaults.StandardUserDefaults.FloatForKey(name).Cast <TPrimitive>();
            }
            else if (type == typeof(long))
            {
                value = MonoTouch.Foundation.NSUserDefaults.StandardUserDefaults.StringForKey(name).ToLong().Cast <TPrimitive>();
            }
            else
            {
                throw new NotImplementedException("");
            }
#endif

            return(value);
        }
        static public bool Login()
        {
            //Login using local stored credentials
            ISharedPreferences preferences = PreferenceManager.GetDefaultSharedPreferences(Application.Context);

            if (preferences.GetBoolean("loged", false))
            {
                if (NewCredentials(preferences.GetString("email", "nomail"), preferences.GetString("password", "nopassword"), preferences.GetString("token", "notoken")))
                {
                    return(true);
                }
            }
            return(false);
        }
Example #24
0
        /// <summary>
        /// Loads bool by key ((If database is not exist, it will be created)(If there is no value by this key, returns default value)).
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="defValue">The default value.</param>
        /// <returns>Bool by key (If database is not exist, or there is not any value by this key, returns default value).</returns>
        public override bool LoadData(string key, bool defValue)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return(defValue);
            }

            if (_preferences == null)
            {
                CreateIfNotExist();
            }

            return(_preferences.GetBoolean(key, defValue));
        }
		public void Initialize(ISharedPreferences pref){
			preference = pref;	
			
			leftPort = StringToMotorPort(preference.GetString("leftPort", "Motor A"));
			rightPort = StringToMotorPort(preference.GetString("rightPort", "Motor C"));
			additionalPort = StringToMotorPort(preference.GetString("additionalPort", "Motor B"));
			
			reverseLeft =  preference.GetBoolean("reverseLeft", false);
			reverseRight = preference.GetBoolean("reverseRight", false);
			reverseAdditional = preference.GetBoolean("reverseAdditional", false);
			
			sendVehicleDataToMailbox = preference.GetBoolean("sendVehicleDataToMailbox", false);
			sensorValueToSpeech = preference.GetBoolean("sensorValueToSpeech", true);
			deviceName = preference.GetString("deviceName", "");
			type = StringToBrickType(preference.GetString("brickType", "EV3"));
			vehicleMailbox = StringToMailbox(preference.GetString("vehicleMailbox", "Mailbox 0"));
			degreeOffset = StringToDegreeOffset(preference.GetString("degreeOffset", "Up"));
			
			sensor1 = preference.GetString("sensor1", "None");
			sensor2 = preference.GetString("sensor2", "None");
			sensor3 = preference.GetString("sensor3", "None");
			sensor4 = preference.GetString("sensor4", "None");
		}
Example #26
0
        /// <summary>
        /// Setup the preferences using the PreferenceManager build inside Android
        /// </summary>
        private void SetupPreferences()
        {
            _preferences = PreferenceManager.GetDefaultSharedPreferences(this);
            _prefsEditor = _preferences.Edit();

            _saveLogin = _preferences.GetBoolean("saveLogin", false);

            if (_saveLogin)
            {
                _usernameEditText.Text     = _preferences.GetString("username", "");
                _passwordEditText.Text     = _preferences.GetString("password", "");
                _saveLoginCheckBox.Checked = true;
            }
        }
Example #27
0
        public void OnSharedPreferenceChanged(ISharedPreferences sharedPreferences, string key)
        {
            var dal = new DAL();

            if (key == PreferencesModel.KEY_NAME_READY)
            {
                var ready = sharedPreferences.GetBoolean("ready", false);
                if (ready)
                {
                    NotifyEvent("Alarma Activada", "");

                    var h = new HistoryItem {
                        Time          = DateTime.Now,
                        State         = Action.ACTION_ID_ACTIVATED,
                        PartitionName = "detector",
                        Detail        = "ALARMA ACTIVADA"
                    };
                    dal.RegiterEvent(h);
                    NotifyNewEvent(h);
                    //StopDetect ();
                    //StartDetect ();
                    RestartDetect();
                }
                else
                {
                    NotifyEvent("Alarma Desactivada", "");
                    //dal.DesactivateAllPartitions ();
                    var h = new HistoryItem {
                        Time          = DateTime.Now,
                        State         = Action.ACTION_ID_DESACTIVATED,
                        PartitionName = "detector",
                        Detail        = "ALARMA DESACTIVADA"
                    };
                    dal.RegiterEvent(h);
                    NotifyNewEvent(h);
                    prefs_model.Fired            = false;
                    prefs_model.Call_Phone_Index = 0;
                    Notificando = false;
                    if (!prefs_model.Teclado_Enabled)
                    {
                        StopDetect();
                    }
                }
            }
            prefs_model.ReloadProperty(key);
            if (key == PreferencesModel.KEY_NAME_TECLADO_ENABLED)
            {
                StopSelf();
            }
        }
Example #28
0
        public static Debt GetDebt(this ISharedPreferences sharedPref, string key)
        {
            var id           = sharedPref.GetIntOrThrow(key + IdSuffix);
            var contact      = sharedPref.GetContact(key + ContactSuffix);
            var money        = sharedPref.GetMoney(key + MoneySuffix);
            var creationDate = sharedPref.GetDate(key + CreationDateSuffix);

            sharedPref.CheckContains(key + CommentSuffix);
            var comment = sharedPref.GetString(key + CommentSuffix, "");

            sharedPref.CheckContains(key + IsPaidSuffix);
            var isPaid = sharedPref.GetBoolean(key + IsPaidSuffix, false);

            sharedPref.CheckContains(key + HasPaymentDateSuffix);
            var hasPaymentDate = sharedPref.GetBoolean(key + HasPaymentDateSuffix, false);

            var debt = hasPaymentDate
                ? new Debt(id, contact, money, comment, creationDate, sharedPref.GetDate(key + PaymentDateSuffix))
                : new Debt(id, contact, money, comment, creationDate);

            debt.IsPaid = isPaid;
            return(debt);
        }
        public static void Init()
        {
            try
            {
                SharedData   = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
                LastPosition = Application.Context.GetSharedPreferences("last_position", FileCreationMode.Private);

                string getValue = SharedData.GetString("Night_Mode_key", string.Empty);
                ApplyTheme(getValue);

                var cdv = InitFloating.CanDrawOverlays(Application.Context);
                if (cdv)
                {
                    SettingsPrefFragment.SChatHead = SharedData.GetBoolean("chatheads_key", cdv);
                }

                SettingsPrefFragment.SSoundControl = SharedData.GetBoolean("checkBox_PlaySound_key", true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        private void ClearPreviousDataOnFirstRun()
        {
            ISharedPreferences prefs         = GetSharedPreferences("firstRun", FileCreationMode.Private);
            bool firstRun                    = prefs.GetBoolean("is_first_run", true);
            bool clearDataForSpecificRelease = DBService.GetDB().ClearExistingData();

            if (firstRun || clearDataForSpecificRelease)
            {
                CommonUtils.GetInstance().ClearAppOfflineData(Utils.StoragePath());
                ISharedPreferencesEditor editor = prefs.Edit();
                editor.PutBoolean("is_first_run", false);
                editor.Apply();
            }
        }
        public void OnSharedPreferenceChanged(ISharedPreferences preferences, String key)
        {
            switch (key)
            {
            case "CheckUpdatesOnStart":
                CheckUpdatesOnStart = preferences.GetBoolean("CheckUpdatesOnStart", true);
                break;

            case "UseFabDateSelector":
                UseFabDateSelector = preferences.GetBoolean("UseFabDateSelector", true);
                break;

            case "UseDarkTheme":
                UseDarkTheme = preferences.GetBoolean("UseDarkTheme", false);
                ThemeChanged?.Invoke();
                break;

            case "DisplaySubjectEndTime":
                DisplaySubjectEndTime = preferences.GetBoolean("DisplaySubjectEndTime", false);
                break;

            case "UpperWeekDate":
                UpperWeekDate = new DateTime(preferences.GetLong("UpperWeekDate", 0));
                break;

            case "CurrentScheduleId":
            case "LastMigrationVersion":
            case "LastSeenUpdateVersion":
            case "LastSeenWelcomeVersion":
            case "StoreReleaseNoticeViewed":
                break;

                //default:
                //    throw new NotSupportedException(
                //        $"Changing parameter \"{key}\" via preferences screen is not supported.");
            }
        }
        /// <summary>
        /// Returns a stored geofence by its ID, or returns null if it's not found
        /// </summary>
        /// <returns>A SimpleGeofence defined by its center and radius, or null if the ID is invalid</returns>
        /// <param name="id">The ID of a stored Geofence</param>
        public override GeofenceCircularRegion Get(String id)
        {
            // Get the latitude for the geofence identified by id, or INVALID_FLOAT_VALUE if it doesn't exist (similarly for the other values that follow)
            double lat                       = mPrefs.GetFloat(GetFieldKey(id, LatitudeGeofenceRegionKey), InvalidFloatValue);
            double lng                       = mPrefs.GetFloat(GetFieldKey(id, LongitudeGeofenceRegionKey), InvalidFloatValue);
            double radius                    = mPrefs.GetFloat(GetFieldKey(id, RadiusGeofenceRegionKey), InvalidFloatValue);
            bool   notifyOnEntry             = mPrefs.GetBoolean(GetFieldKey(id, NotifyOnEntryGeofenceRegionKey), false);
            bool   notifyOnExit              = mPrefs.GetBoolean(GetFieldKey(id, NotifyOnExitGeofenceRegionKey), false);
            bool   notifyOnStay              = mPrefs.GetBoolean(GetFieldKey(id, NotifyOnStayGeofenceRegionKey), false);
            string notificationEntryMessage  = mPrefs.GetString(GetFieldKey(id, NotificationEntryMessageGeofenceRegionKey), string.Empty);
            string notificationExitMessage   = mPrefs.GetString(GetFieldKey(id, NotificationExitMessageGeofenceRegionKey), string.Empty);
            string notificationStayMessage   = mPrefs.GetString(GetFieldKey(id, NotificationStayMessageGeofenceRegionKey), string.Empty);
            bool   showNotification          = mPrefs.GetBoolean(GetFieldKey(id, ShowNotificationGeofenceRegionKey), false);
            bool   persistent                = mPrefs.GetBoolean(GetFieldKey(id, PersistentGeofenceRegionKey), false);
            bool   showEntryNotification     = mPrefs.GetBoolean(GetFieldKey(id, ShowEntryNotificationGeofenceRegionKey), false);
            bool   showExitNotification      = mPrefs.GetBoolean(GetFieldKey(id, ShowExitNotificationGeofenceRegionKey), false);
            bool   showStayNotification      = mPrefs.GetBoolean(GetFieldKey(id, ShowStayNotificationGeofenceRegionKey), false);
            int    stayedInThresholdDuration = mPrefs.GetInt(GetFieldKey(id, StayedInThresholdDurationGeofenceRegionKey), InvalidIntValue);

            //long expirationDuration = mPrefs.GetLong(GetFieldKey(id, ExpirationDurationGeofenceRegionKey), InvalidLongValue);
            //int transitionType = mPrefs.GetInt(GetFieldKey(id, TransitionTypeGeofenceRegionKey), InvalidIntValue);

            // If none of the values is incorrect, return the object
            if (lat != InvalidFloatValue &&
                lng != InvalidFloatValue &&
                radius != InvalidFloatValue &&
                persistent &&
                stayedInThresholdDuration != InvalidIntValue
                // && expirationDuration != InvalidLongValue
                //&& transitionType != InvalidIntValue
                )
            {
                return new GeofenceCircularRegion(id, lat, lng, radius, notifyOnEntry, notifyOnExit, notifyOnStay, showNotification, persistent,
                                                  showEntryNotification, showExitNotification, showStayNotification)
                       {
                           NotificationEntryMessage = notificationEntryMessage,
                           NotificationStayMessage  = notificationStayMessage,
                           NotificationExitMessage  = notificationExitMessage,

                           StayedInThresholdDuration = TimeSpan.FromMilliseconds(stayedInThresholdDuration)
                       }
            }
            ;

            // Otherwise return null
            return(null);
        }
Example #33
0
        public void LoadUserPreferences()
        {
            try
            {
                Preferences = PreferenceManager.GetDefaultSharedPreferences(Activity);

                //////////////////////////////////////////////////////////////////////////
                // APP OBJECTS
                //////////////////////////////////////////////////////////////////////////
                ArticleNavigation = JsonConvert.DeserializeObject <Dictionary <string, NavStruct> >(Preferences.GetString("ArticleNavigation", ""));
                Libraries         = JsonConvert.DeserializeObject <List <Library> >(Preferences.GetString("Libraries", ""));
                CurrentLibrary    = Libraries.FirstOrDefault();

                //////////////////////////////////////////////////////////////////////////
                // VARIABLES
                //////////////////////////////////////////////////////////////////////////
                WebviewWeights    = JsonConvert.DeserializeObject <float[]>(Preferences.GetString("WebviewWeights", ""));
                SeekBarTextSize   = Preferences.GetInt("WebViewBaseFontSize", 16);
                CurrentScreenMode = (ScreenMode)Preferences.GetInt("CurrentScreenMode", 0);

                //////////////////////////////////////////////////////////////////////////
                // LANGUAGE
                //////////////////////////////////////////////////////////////////////////
                Swapped           = Preferences.GetBoolean("Swapped", false);
                PinyinToggle      = Preferences.GetBoolean("PinyinToggle", false);
                PrimaryLanguage   = App.FUNCTIONS.GetAvailableLanguages(Activity).Where(l => l.EnglishName == Preferences.GetString("PrimaryLanguage", "")).First();
                SecondaryLanguage = App.FUNCTIONS.GetAvailableLanguages(Activity).Where(l => l.EnglishName == Preferences.GetString("SecondaryLanguage", "")).First();
                PinyinLanguage    = App.FUNCTIONS.GetAvailableLanguages(Activity).Where(l => l.EnglishName == Preferences.GetString("PinyinLanguage", "")).First();
                Language          = Preferences.GetString("Language", Language);

                Console.WriteLine("Awesome, preferences are loaded!");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Example #34
0
        public static void CheckProtectedAppsFeature(Context context)
        {
            IMvxTextProvider   textProvider      = (IMvxTextProvider)Mvx.get_IoCProvider().Resolve <IMvxTextProvider>();
            string             text1             = textProvider.GetText((string)null, (string)null, "ProtectedAppsCheckerTitle");
            string             text2             = textProvider.GetText((string)null, (string)null, "ProtectedAppsCheckerContent");
            string             text3             = textProvider.GetText((string)null, (string)null, "ProtectedAppsCheckerAccept");
            string             text4             = textProvider.GetText((string)null, (string)null, "ProtectedAppsCheckerCancel");
            ISharedPreferences sharedPreferences = context.GetSharedPreferences("ProtectedApps", (FileCreationMode)0);

            if (sharedPreferences.GetBoolean("skipAppListMessage", false))
            {
                return;
            }
            bool flag = false;
            ISharedPreferencesEditor editor = sharedPreferences.Edit();

            using (List <Intent> .Enumerator enumerator = ProtectedAppsChecker.PowermanagerIntents.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    Intent intent = enumerator.Current;
                    if (context.get_PackageManager().ResolveActivity(intent, (PackageInfoFlags)65536) != null)
                    {
                        new AlertDialog.Builder(context).SetTitle(text1).SetMessage(text2).SetPositiveButton(text3, (EventHandler <DialogClickEventArgs>)((o, d) =>
                        {
                            editor.PutBoolean("skipAppListMessage", true);
                            editor.Apply();
                            try
                            {
                                context.StartActivity(intent);
                            }
                            catch (Exception ex)
                            {
                                ErrorHandler.Current.HandleError(ex);
                                new AlertDialog.Builder(context).SetTitle(textProvider.GetText((string)null, (string)null, "ProtectedAppsErrorTitle")).SetMessage(textProvider.GetText((string)null, (string)null, "ProtectedAppsErrorContent")).SetCancelable(false).SetPositiveButton(textProvider.GetText((string)null, (string)null, "ProtectedAppsAcceptButtonText"), (EventHandler <DialogClickEventArgs>)((_param1, _param2) => {})).Show();
                            }
                        })).SetNegativeButton(text4, (EventHandler <DialogClickEventArgs>)((o, d) => {})).SetCancelable(false).Show();
                        flag = true;
                        break;
                    }
                }
            }
            if (flag)
            {
                return;
            }
            editor.PutBoolean("skipAppListMessage", true);
            editor.Apply();
        }
Example #35
0
      public async void agregarPartida(object sender, EventArgs e)
      {
          ISharedPreferences preferences = PreferenceManager.GetDefaultSharedPreferences(this);


          string myValue = "";

          PartidasModel partida = new PartidasModel();

          partida.cantidad   = Convert.ToInt32(txtcantidad.Text);
          partida.productoId = id.ToString();
          if (preferences.GetBoolean("is_login", false))
          {
              myValue = preferences.GetString("token", "");
          }
          else
          {
              myValue = preferences.GetString("NotToken", "");
          }
          partida.idCarrito = preferences.GetString("name", "");
          partida.id        = Guid.NewGuid().ToString();
          partida.nombre    = nombre;
          //partida.costo = 12;
          partida.pedidoId = "hola";
          partida.costo    = costo * Convert.ToInt32(txtcantidad.Text);
          string baseurl = "http://pushstart.azurewebsites.net/Carrito/agregar";
          var    Client  = new HttpClient();

          Client.MaxResponseContentBufferSize = 256000;
          var           uri      = new Uri(baseurl);
          var           json     = JsonConvert.SerializeObject(partida);
          StringContent content  = new StringContent(json, Encoding.UTF8, "application/json");
          var           response = Client.PostAsync(uri, content).Result;

          if (response.IsSuccessStatusCode)
          {
              Toast.MakeText(this, "Exito", ToastLength.Short).Show();
          }
          else
          {
              Toast.MakeText(this, "Ocurrio un error :c", ToastLength.Short).Show();
          }



          Intent intento2 = new Intent(this, typeof(MenuActivity));

          StartActivity(intento2);
      }
Example #36
0
        private void SetTodokesakiAsync()
        {
            string soukoCd    = prefs.GetString("souko_cd", "");
            string kitakuCd   = prefs.GetString("kitaku_cd", "");
            string syuka_date = prefs.GetString("syuka_date", "");

            if (prefs.GetBoolean("kounaiFlag", true))
            {
                vendorList = WebService.RequestKosu190();;
            }
            else
            {
                vendorList = new List <KOSU190>();
                List <MateFile> mateList = new MateFileHelper().SelectAll();

                string tempVendorCd = "";

                foreach (MateFile mfile in mateList)
                {
                    // ベンダーに紐づくマテハン情報も複数持つので、ベンダーコードで分ける
                    if (tempVendorCd != mfile.vendor_cd)
                    {
                        tempVendorCd = mfile.vendor_cd;

                        KOSU190 kosu190 = new KOSU190();
                        kosu190.vendor_cd = mfile.vendor_cd;
                        kosu190.vendor_nm = mfile.vendor_nm;

                        vendorList.Add(kosu190);
                    }
                }
            }

            if (vendorList.Count > 0)
            {
                ListView listView = view.FindViewById <ListView>(Resource.Id.listView1);
                listView.ItemClick += listView_ItemClick;

                vendorAdapter    = new VendorAllAdapter(vendorList);
                listView.Adapter = vendorAdapter;
            }
            else
            {
                ShowDialog("報告", "表示データがありません。", () =>
                {
                    FragmentManager.PopBackStack();
                });
            }
        }
Example #37
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            ISharedPreferences pref = Application.Context.GetSharedPreferences
                                          ("_bitopi_UserInfo", FileCreationMode.Private);

            repo         = new ProductionRepository(ShowLoader, HideLoader);
            LastLocation = pref.GetBoolean("IsLastLocation", false);
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.ProcessList);
            SupportActionBar.SetDisplayShowCustomEnabled(true);
            SupportActionBar.SetCustomView(Resource.Layout.custom_actionbar);
            InitializeControl();
            InitializeEvent();
            base.LoadDrawerView();
        }
 public void ActivateKeyboardIfAppropriate(bool closeAfterCreate, ISharedPreferences prefs)
 {
     if (prefs.GetBoolean("kp2a_switch_rooted", false))
     {
         //switch rooted
         bool onlySwitchOnSearch = prefs.GetBoolean(
             GetString(Resource.String.OpenKp2aKeyboardAutomaticallyOnlyAfterSearch_key), false);
         if (closeAfterCreate || (!onlySwitchOnSearch))
         {
             ActivateKp2aKeyboard();
         }
     }
     else
     {
         //if the app is about to be closed again (e.g. after searching for a URL and returning to the browser:
         // automatically bring up the Keyboard selection dialog
         if ((closeAfterCreate) &&
             prefs.GetBoolean(GetString(Resource.String.OpenKp2aKeyboardAutomatically_key),
                              Resources.GetBoolean(Resource.Boolean.OpenKp2aKeyboardAutomatically_default)))
         {
             ActivateKp2aKeyboard();
         }
     }
 }
Example #39
0
        // Launches the startup task
        protected override void OnResume()
        {
            base.OnResume();
            AppPreferences(this);

            if (SharedPrefs.GetBoolean("Bool", false) == true)
            {
                Intent intent = new Intent(this, typeof(EntranceActivity));
                StartActivity(intent);
            }
            else
            {
                StartActivity(new Intent(Application.Context, typeof(MainActivity)));
            }
        }
Example #40
0
        public void Initialize(ISharedPreferences pref)
        {
            preference = pref;

            leftPort       = StringToMotorPort(preference.GetString("leftPort", "Motor A"));
            rightPort      = StringToMotorPort(preference.GetString("rightPort", "Motor C"));
            additionalPort = StringToMotorPort(preference.GetString("additionalPort", "Motor B"));

            reverseLeft       = preference.GetBoolean("reverseLeft", false);
            reverseRight      = preference.GetBoolean("reverseRight", false);
            reverseAdditional = preference.GetBoolean("reverseAdditional", false);

            sendVehicleDataToMailbox = preference.GetBoolean("sendVehicleDataToMailbox", false);
            sensorValueToSpeech      = preference.GetBoolean("sensorValueToSpeech", true);
            deviceName     = preference.GetString("deviceName", "");
            type           = StringToBrickType(preference.GetString("brickType", "EV3"));
            vehicleMailbox = StringToMailbox(preference.GetString("vehicleMailbox", "Mailbox 0"));
            degreeOffset   = StringToDegreeOffset(preference.GetString("degreeOffset", "Up"));

            sensor1 = preference.GetString("sensor1", "None");
            sensor2 = preference.GetString("sensor2", "None");
            sensor3 = preference.GetString("sensor3", "None");
            sensor4 = preference.GetString("sensor4", "None");
        }
		public void OnSharedPreferenceChanged(ISharedPreferences sharedPreferences, System.String key) {

			if (key.Equals(KEY_PORT)) {
				int port = Integer.ParseInt(sharedPreferences.GetString(KEY_PORT, mPort.ToString()));
				if (port != mPort) {
					mPort = port;
					mRestart = true;
					start();
				}
			}		
			else if (key.Equals(KEY_ENABLED)) {
				mEnabled = sharedPreferences.GetBoolean(KEY_ENABLED, mEnabled);
				start();
			}
		}
Example #42
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);
            SetContentView (Resource.Layout.welcome);

            prefs = GetPreferences (FileCreationMode.Append);
            firstTime = prefs.GetBoolean (FIRST, true);
            if (firstTime) {
                MakeQuestionDB ();
                MakeScoreDB ();
                editor = prefs.Edit ();
                editor.PutBoolean (FIRST, false);
                editor.Commit ();

            }

            Button button = FindViewById<Button> (Resource.Id.btnStarQuiz);
            button.Click += delegate {
                StartActivity (typeof(QuizActivity));
                Finish ();
            };
        }
		public void GetPreferences() {
			prefs = PreferenceManager.GetDefaultSharedPreferences(this);
			prefAutoDownload = prefs.GetBoolean ("prefAutoDownload", false);
			prefEnableNotifications = prefs.GetBoolean ("prefEnableNotifications", true);
			prefShowAppUpdates = prefs.GetBoolean ("prefShowAppUpdates", true);
			prefHoursNotifications = int.Parse(prefs.GetString ("prefHoursNotifications", "4"))-1;
			if (prefHoursNotifications == 1) {
				millisecondsNotifications = 3 * 60 * 60 * 1000;
			} else if (prefHoursNotifications == 2) {
				millisecondsNotifications = 6 * 60 * 60 * 1000;
			} else if (prefHoursNotifications == 3) {
				millisecondsNotifications = 9 * 60 * 60 * 1000;
			} else if (prefHoursNotifications == 4) {
				millisecondsNotifications = 12 * 60 * 60 * 1000;
			} else if (prefHoursNotifications == 5) {
				millisecondsNotifications = 24 * 60 * 60 * 1000;
			} else {
				millisecondsNotifications = 12 * 60 * 60 * 1000;
			}

			SetNotification ();
		}
Example #44
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);
            Window.RequestFeature (WindowFeatures.NoTitle);
            SetContentView (Resource.Layout.Main);
            Window.SetBackgroundDrawableResource (Resource.Drawable.empty);
            Window.SetFeatureInt (WindowFeatures.NoTitle,0);
            Window.ClearFlags (WindowManagerFlags.DimBehind);

            kalinga = Typeface.CreateFromAsset (this.Assets, "fonts/kalinga.ttf");
            kalingab = Typeface.CreateFromAsset (this.Assets, "fonts/kalingab.ttf");

            prefs = GetPreferences (FileCreationMode.Append);
            firstTime = prefs.GetBoolean (FIRST, true);
            tSel = prefs.GetBoolean (TIMESEL, true);

            flipper = FindViewById<ViewFlipper> (Resource.Id.viewFlipper1);
            viewStart = FindViewById<LinearLayout> (Resource.Id.view1);
            viewSearch = FindViewById<LinearLayout> (Resource.Id.view2);
            ibSearch = FindViewById<ImageButton> (Resource.Id.ibSearch);
            ibTravel = FindViewById<ImageButton> (Resource.Id.ibTravel);
            ibPrevious = FindViewById<ImageButton> (Resource.Id.ibPrevious);
            main = FindViewById<LinearLayout> (Resource.Id.llMain);
            from = FindViewById<TextView> (Resource.Id.tvFrom);
            fromInput = FindViewById<AutoCompleteTextView> (Resource.Id.atvFrom);
            toInput = FindViewById<AutoCompleteTextView> (Resource.Id.atvTo);
            to = FindViewById<TextView> (Resource.Id.tvTo);
            dateLabel = FindViewById<Button> (Resource.Id.tvDate);
            timeLabel = FindViewById<Button> (Resource.Id.tvTime);
            rbDepart = FindViewById<RadioButton> (Resource.Id.rbDeparture);
            rbArrive = FindViewById<RadioButton> (Resource.Id.rbArrival);
            var dateButton = FindViewById<ImageButton> (Resource.Id.btnDate);
            var timeButton = FindViewById<ImageButton> (Resource.Id.btnTime);
            var btnGo = FindViewById<Button> (Resource.Id.btnGo);

            dateButton.Click += DatePicker_Dialog;
            dateLabel.Click += DatePicker_Dialog;
            timeButton.Click += TimePicker_Dialog;
            timeLabel.Click += TimePicker_Dialog;
            btnGo.Click += Download_Itinerary;
            rbDepart.Click += RadioButtonClick;
            rbArrive.Click += RadioButtonClick;
            btnGo.Click += CloseKeyBoard;
            main.Click += CloseKeyBoard;
            from.Click += ShowFocus;
            to.Click += ShowFocus;
            fromInput.TextChanged += ChangeGravity;
            toInput.TextChanged += ChangeGravity;
            ibSearch.Click += NextView;
            ibPrevious.Click += PreviousView;
            ibTravel.Click += delegate {
                StartActivity (typeof (ActivityUnderConstruction));
            };

            DateTime now = DateTime.Now;
            var day = XTool.CatchZero (now.Day);
            var month = XTool.CatchZero (now.Month);
            var year = XTool.CatchZero (now.Year - 2000);
            var hour = XTool.CatchZero (now.Hour);
            var minute = XTool.CatchZero (now.Minute);

            RunOnUiThread (() => {
                dateLabel.Text = String.Format ("{0}/{1}/{2}", day, month, year);
                timeLabel.Text = String.Format ("{0}:{1}", hour, minute);

                rbDepart.Checked = tSel;
                rbArrive.Checked = !tSel;
                from.Typeface = kalinga;
                fromInput.Typeface = kalingab;
                to.Typeface = kalinga;
                toInput.Typeface = kalingab;
                dateLabel.Typeface = kalinga;
                timeLabel.Typeface = kalinga;
                rbArrive.Typeface = tSel ? kalinga : kalingab;
                rbDepart.Typeface = tSel ? kalingab : kalinga;
                btnGo.Typeface = kalingab;
            });

            if (firstTime) {
                Download_Stations ();
            } else {
            //				using (StreamReader reader = new StreamReader(Assets.Open ("stations.txt")))
            //				{
            //					var line = reader.ReadToEnd ();
            //					reader.Close ();
            //					SaveStations (line);
            //				}
            }

            var dbStation = new StationCommands (this);
            List<string> list = new List<string> ();
            list = dbStation.All;
            dbStation.Close ();
            autoCompleteAdapter = new ArrayAdapter (this, Resource.Layout.autocomplete, list.ToArray ());
            fromInput.Adapter = autoCompleteAdapter;
            toInput.Adapter = autoCompleteAdapter;
        }
Example #45
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            _design.ApplyTheme();

            //use FlagSecure to make sure the last (revealed) character of the master password is not visible in recent apps
            if (PreferenceManager.GetDefaultSharedPreferences(this).GetBoolean(
                GetString(Resource.String.ViewDatabaseSecure_key), true))
            {
                Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);
            }

            Intent i = Intent;

            //only load the AppTask if this is the "first" OnCreate (not because of kill/resume, i.e. savedInstanceState==null)
            // and if the activity is not launched from history (i.e. recent tasks) because this would mean that
            // the Activity was closed already (user cancelling the task or task complete) but is restarted due recent tasks.
            // Don't re-start the task (especially bad if tak was complete already)
            if (Intent.Flags.HasFlag(ActivityFlags.LaunchedFromHistory))
            {
                AppTask = new NullTask();
            }
            else
            {
                AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);
            }

            String action = i.Action;

            _prefs = PreferenceManager.GetDefaultSharedPreferences(this);
            _rememberKeyfile = _prefs.GetBoolean(GetString(Resource.String.keyfile_key), Resources.GetBoolean(Resource.Boolean.keyfile_default));

            _ioConnection = new IOConnectionInfo();

            if (action != null && action.Equals(ViewIntent))
            {
                if (!GetIocFromViewIntent(i)) return;
            }
            else if ((action != null) && (action.Equals(Intents.StartWithOtp)))
            {
                if (!GetIocFromOtpIntent(savedInstanceState, i)) return;
                _keepPasswordInOnResume = true;
            }
            else
            {
                SetIoConnectionFromIntent(_ioConnection, i);
                var keyFileFromIntent = i.GetStringExtra(KeyKeyfile);
                if (keyFileFromIntent != null)
                {
                    Kp2aLog.Log("try get keyfile from intent");
                    _keyFileOrProvider = IOConnectionInfo.SerializeToString(IOConnectionInfo.FromPath(keyFileFromIntent));
                    Kp2aLog.Log("try get keyfile from intent ok");
                }
                else
                {
                    _keyFileOrProvider = null;
                }
                _password = i.GetStringExtra(KeyPassword) ?? "";
                if (string.IsNullOrEmpty(_keyFileOrProvider))
                {
                    _keyFileOrProvider = GetKeyFile(_ioConnection.Path);
                }
                if ((!string.IsNullOrEmpty(_keyFileOrProvider)) || (_password != ""))
                {
                    _keepPasswordInOnResume = true;
                }
            }

            if (App.Kp2a.GetDb().Loaded && App.Kp2a.GetDb().Ioc != null &&
                App.Kp2a.GetDb().Ioc.GetDisplayName() != _ioConnection.GetDisplayName())
            {
                // A different database is currently loaded, unload it before loading the new one requested
                App.Kp2a.LockDatabase(false);
            }

            SetContentView(Resource.Layout.password);
            InitializeFilenameView();

            if (KeyProviderType == KeyProviders.KeyFile)
            {
                UpdateKeyfileIocView();
            }

            FindViewById<EditText>(Resource.Id.password).TextChanged +=
                (sender, args) =>
                {
                    _password = FindViewById<EditText>(Resource.Id.password).Text;
                    UpdateOkButtonState();
                };
            FindViewById<EditText>(Resource.Id.password).EditorAction += (sender, args) =>
                {
                    if ((args.ActionId == ImeAction.Done) || ((args.ActionId == ImeAction.ImeNull) && (args.Event.Action == KeyEventActions.Down)))
                        OnOk();
                };

            FindViewById<EditText>(Resource.Id.pass_otpsecret).TextChanged += (sender, args) => UpdateOkButtonState();

            EditText passwordEdit = FindViewById<EditText>(Resource.Id.password);
            passwordEdit.Text = _password;
            passwordEdit.RequestFocus();
            Window.SetSoftInputMode(SoftInput.StateVisible);

            InitializeOkButton();

            InitializePasswordModeSpinner();

            InitializeOtpSecretSpinner();

            UpdateOkButtonState();

            InitializeTogglePasswordButton();
            InitializeKeyfileBrowseButton();

            InitializeQuickUnlockCheckbox();

            RestoreState(savedInstanceState);

            if (i.GetBooleanExtra("launchImmediately", false))
            {
                App.Kp2a.GetFileStorage(_ioConnection)
                       .PrepareFileUsage(new FileStorageSetupInitiatorActivity(this, OnActivityResult, null), _ioConnection,
                                         RequestCodePrepareDbFile, false);
            }
        }
Example #46
0
		private void InitView()
		{
			//设置标题栏
			var img_header_back = FindViewById<ImageView> (Resource.Id.img_header_back);
			img_header_back.Click += (sender, e) => 
			{
				this.Finish();
				OverridePendingTransition(Resource.Animation.bottom_out,0);
			};

			var tv_back = FindViewById<TextView> (Resource.Id.tv_back);
			tv_back.Text = "";
			var tv_desc = FindViewById<TextView> (Resource.Id.tv_desc);
			tv_desc.Text = "登录";



			_jpushUtil = new JPushUtil (this);
			// Create your application here
			//或得共享实例变量
			sp_userinfo = this.GetSharedPreferences(Global.SHAREDPREFERENCES_USERINFO,FileCreationMode.Private);
			//获得实例对象
			edit_userName = FindViewById<EditText>(Resource.Id.edit_UserName);
			edit_userPassword = FindViewById<EditText> (Resource.Id.edit_PassWord);
			cb_passWord = FindViewById<CheckBox> (Resource.Id.cb_Password);
			btn_login = FindViewById<Button> (Resource.Id.btn_Login);
			tv_Register = FindViewById<TextView> (Resource.Id.tv_Register);
			var tv_forgetPwd = FindViewById<TextView> (Resource.Id.tv_forgetPwd);
			var img_eye = FindViewById<ImageView> (Resource.Id.img_eye);
			img_eye.Click += (sender, e) => 
			{
				if(edit_userPassword.InputType == (Android.Text.InputTypes.ClassText|Android.Text.InputTypes.TextVariationPassword))
				{
					edit_userPassword.InputType = Android.Text.InputTypes.ClassText|Android.Text.InputTypes.TextVariationVisiblePassword;
					img_eye.SetImageResource(Resource.Drawable.ic_login_eye_selected);
				}
				else if(edit_userPassword.InputType == (Android.Text.InputTypes.ClassText| Android.Text.InputTypes.TextVariationVisiblePassword))
				{
					edit_userPassword.InputType = Android.Text.InputTypes.ClassText|Android.Text.InputTypes.TextVariationPassword;
					img_eye.SetImageResource(Resource.Drawable.ic_login_eye_normal);
				}

			};

			//点击注册
			tv_Register.Click += (sender, e) => 
			{
				
				StartActivity(typeof(RegisterStepOneActivity));
				OverridePendingTransition(Android.Resource.Animation.SlideInLeft,Android.Resource.Animation.SlideOutRight);
			};

			//找回密码
			tv_forgetPwd.Click += (sender, e) => 
			{
				var intent = new Intent(this,typeof(SendSecurityCodeActivity));
				var sendbundle = new Bundle();
				sendbundle.PutString("SendType","FindPwd");
				sendbundle.PutString("PhoneNumber",string.Empty);
				intent.PutExtras(sendbundle);
				StartActivity(intent);
				OverridePendingTransition(Android.Resource.Animation.SlideInLeft,Android.Resource.Animation.SlideOutRight);
			};

			//如果选择了记住密码,则赋值
			if (sp_userinfo.GetBoolean (Global.refrence_Password_Check, false)) {
				cb_passWord.Checked = true;
				edit_userName.Text = sp_userinfo.GetString (Global.refrence_UserName, string.Empty);
				edit_userPassword.Text = sp_userinfo.GetString (Global.refrence_Password, string.Empty);
			}



			//记住密码选择事件
			cb_passWord.CheckedChange += (sender, e) => 
			{
				if(cb_passWord.Checked)
					sp_userinfo.Edit().PutBoolean(Global.refrence_Password_Check,true).Commit();
				else
					sp_userinfo.Edit().PutBoolean(Global.refrence_Password_Check,false).Commit();
			};


			//登录按钮事件
			btn_login.Click += (sender, e) => 
			{

				Login();
			};
		}
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
        {
            if (requestCode == FINGERPRINT_PERMISSION_REQUEST_CODE && grantResults[0] == Android.Content.PM.Permission.Granted) {
                SetContentView (Resource.Layout.activity_main);
                var purchaseButton = FindViewById<Button> (Resource.Id.purchase_button);

                if (!mKeyguardManager.IsKeyguardSecure) {
                    purchaseButton.Enabled = false;
                    // Show a message that the user hasn't set up a fingerprint or lock screen.
                    Toast.MakeText (this, "Secure lock screen hasn't set up.\n"
                        + "Go to 'Settings -> Security -> Fingerprint' to set up a fingerprint", ToastLength.Long).Show ();
                    return;
                }

                mFingerprintManager = (FingerprintManager)GetSystemService (Context.FingerprintService);
                if (!mFingerprintManager.HasEnrolledFingerprints) {
                    purchaseButton.Enabled = false;
                    // This happens when no fingerprints are registered.
                    Toast.MakeText (this, "Go to 'Settings -> Security -> Fingerprint' " +
                        "and register at least one fingerprint", ToastLength.Long).Show ();
                    return;
                }

                CreateKey ();
                purchaseButton.Enabled = true;
                purchaseButton.Click += (sender, e) => {
                    // Show the fingerprint dialog. The user has the option to use the fingerprint with
                    // crypto, or you can fall back to using a server-side verified password.
                    FindViewById (Resource.Id.confirmation_message).Visibility = ViewStates.Gone;
                    FindViewById (Resource.Id.encrypted_message).Visibility = ViewStates.Gone;

                    mFragment = new FingerprintAuthenticationDialogFragment ();
                    mSharedPreferences = this.GetPreferences (FileCreationMode.Private);

                    if (InitCipher ()) {
                        mFragment.SetCryptoObject (new FingerprintManager.CryptoObject (mCipher));
                        var useFingerprintPreference = mSharedPreferences.GetBoolean (GetString (Resource.String.use_fingerprint_to_authenticate_key), true);
                        if (useFingerprintPreference) {
                            mFragment.SetStage (FingerprintAuthenticationDialogFragment.Stage.Fingerprint);
                        } else {
                            mFragment.SetStage (FingerprintAuthenticationDialogFragment.Stage.Password);
                        }
                        mFragment.Show (FragmentManager, DIALOG_FRAGMENT_TAG);
                    } else {
                        mFragment.SetCryptoObject (new FingerprintManager.CryptoObject (mCipher));
                        mFragment.SetStage (FingerprintAuthenticationDialogFragment.Stage.NewFingerprintEnrolled);
                        mFragment.Show (FragmentManager, DIALOG_FRAGMENT_TAG);
                    }
                };
            }
        }
Example #48
0
 public static bool GetBool(ISharedPreferences prefs, string key, bool def = false)
 {
     return prefs.GetBoolean(key, def);
 }