Пример #1
0
        public static void initDataManager(Context context)
        {
            upSharedPrefs = PreferenceManager.GetDefaultSharedPreferences(context);

            Log.Debug(UPLog.TAG, "Datamanger inited");
        }
Пример #2
0
        public async Task UpdaterAsync(CancellationToken ct)
        {
            string[,] sizesSlugsArr = { { "s-1vcpu-1gb", "5$/month\n1 vCPU : 1GB\n25gb Disk : 1TB Transfer\n"  },
                                        { "s-1vcpu-2gb", "10$/month\n1 vCPU : 2GB\n50gb Disk : 2TB Transfer\n" },
                                        { "s-1vcpu-3gb", "15$/month\n1 vCPU : 3GB\n60gb Disk : 3TB Transfer\n" },
                                        { "s-2vcpu-2gb", "15$/month\n2 vCPU : 2GB\n60gb Disk : 3TB Transfer\n" },
                                        { "s-3vcpu-1gb", "15$/month\n3 vCPU : 1GB\n60gb Disk : 3TB Transfer\n" },
                                        { "s-2vcpu-4gb", "20$/month\n2 vCPU : 4GB\n80gb Disk : 4TB Transfer\n" }, };

            _Loading_Fragment = new Loading_Fragment();
            _Step2_Fragment   = new Step2_Fragment();

            var currentdrops         = new List <DisplayInfo>();
            var regionsslug          = new List <DisplayInfo>();
            ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
            var api_key = prefs.GetString("api_key", null);

            DigitalOceanClient client = new DigitalOceanClient(api_key);

            var trans = SupportFragmentManager.BeginTransaction();

            trans.Add(Resource.Id.Step2_Frame, _Step2_Fragment, "Fragment");
            trans.Add(Resource.Id.Step2_Frame, _Loading_Fragment, "Fragment");
            trans.Hide(_Step2_Fragment);
            trans.Show(_Loading_Fragment);
            trans.Commit();

            var dropletsizes = await client.Sizes.GetAll();

            var regions = await client.Regions.GetAll();

            var trans2 = SupportFragmentManager.BeginTransaction();

            trans2.Hide(_Loading_Fragment);
            trans2.Show(_Step2_Fragment);
            trans2.Commit();

            RadioGroup rgp = FindViewById <RadioGroup>(Resource.Id.radiogroupplan);
            RadioGroup rgr = FindViewById <RadioGroup>(Resource.Id.radiogroupregion);

            for (int i = 0; i < dropletsizes.Count; i++)
            {
                for (int x = 0; x < sizesSlugsArr.GetLength(0); x++)
                {
                    if (dropletsizes[i].Slug == sizesSlugsArr[x, 0] /*&& dropletsizes[i].Available*/)
                    {
                        RadioButton rdbtn = new RadioButton(this);
                        rdbtn.Text = sizesSlugsArr[x, 1];
                        rdbtn.Id   = View.GenerateViewId();
                        var toadd = new DisplayInfo();
                        toadd.dropindex = i;
                        toadd.radioid   = rdbtn.Id;
                        toadd.slug      = sizesSlugsArr[x, 0];
                        toadd.text      = sizesSlugsArr[x, 1];
                        currentdrops.Add(toadd);
                        rgp.AddView(rdbtn);
                    }
                }
                Console.WriteLine(dropletsizes[i].Slug);
            }

            for (int i = 0; i < regions.Count; i++)
            {
                if (regions[i].Available == true)
                {
                    var x = new DisplayInfo();
                    x.name = regions[i].Name;
                    x.slug = regions[i].Slug;
                    regionsslug.Add(x);
                }
            }

            regionsslug.Sort(new Comparison <DisplayInfo>((x, y) => string.Compare(x.name, y.name)));

            for (int i = 0; i < regionsslug.Count; i++)
            {
                RadioButton rdbtn = new RadioButton(this);
                rdbtn.Text             = regionsslug[i].name;
                rdbtn.Id               = View.GenerateViewId();
                regionsslug[i].radioid = rdbtn.Id;
                rgr.AddView(rdbtn);
            }

            RadioButton checkedrgp = FindViewById <RadioButton>(rgp.CheckedRadioButtonId);
            RadioButton checkedrgr = FindViewById <RadioButton>(rgr.CheckedRadioButtonId);

            rgp.CheckedChange += (o, e) =>
            {
                checkedrgp = FindViewById <RadioButton>(rgp.CheckedRadioButtonId);
                for (int i = 0; i < currentdrops.Count; i++)
                {
                    if (currentdrops[i].radioid == checkedrgp.Id)
                    {
                        createdrop.SizeSlug = currentdrops[i].slug;
                        break;
                    }
                }
            };

            rgr.CheckedChange += (o, e) =>
            {
                checkedrgr = FindViewById <RadioButton>(rgr.CheckedRadioButtonId);
                for (int i = 0; i < regionsslug.Count; i++)
                {
                    if (regionsslug[i].radioid == checkedrgr.Id)
                    {
                        createdrop.RegionSlug = regionsslug[i].slug;
                        break;
                    }
                }
            };

            Button next = FindViewById <Button>(Resource.Id.NextS2);
            Button back = FindViewById <Button>(Resource.Id.BackS2);

            back.Click += (o, e) =>
            {
                var intent = new Intent(this, typeof(Step1Activity));
                StartActivity(intent);
            };

            next.Click += (o, e) =>
            {
                if (checkedrgp == null)
                {
                    Toast.MakeText(this, "Please select plan", ToastLength.Short).Show();
                    return;
                }
                if (checkedrgr == null)
                {
                    Toast.MakeText(this, "Please select region", ToastLength.Short).Show();
                    return;
                }

                var intent = new Intent(this, typeof(Step3Activity));
                intent.PutExtra("DropletName", createdrop.Name);
                intent.PutExtra("DropletDistro", Intent.Extras.GetString("DropletDistro"));
                intent.PutExtra("DropletRegion", createdrop.RegionSlug);
                intent.PutExtra("DropletSize", createdrop.SizeSlug);
                StartActivity(intent);
            };
        }
Пример #3
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);

            long usageCount = prefs.GetLong(GetString(Resource.String.UsageCount_key), 0);

            ISharedPreferencesEditor edit = prefs.Edit();

            edit.PutLong(GetString(Resource.String.UsageCount_key), usageCount + 1);
            edit.Commit();

            _showPassword =
                !prefs.GetBoolean(GetString(Resource.String.maskpass_key), Resources.GetBoolean(Resource.Boolean.maskpass_default));

            RequestWindowFeature(WindowFeatures.IndeterminateProgress);

            _activityDesign.ApplyTheme();
            base.OnCreate(savedInstanceState);



            SetEntryView();

            Database db = App.Kp2a.GetDb();

            // Likely the app has been killed exit the activity
            if (!db.Loaded || (App.Kp2a.QuickLocked))
            {
                Finish();
                return;
            }

            SetResult(KeePass.ExitNormal);

            Intent i    = Intent;
            PwUuid uuid = new PwUuid(MemUtil.HexStringToByteArray(i.GetStringExtra(KeyEntry)));

            _pos = i.GetIntExtra(KeyRefreshPos, -1);

            _appTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);

            Entry = db.Entries[uuid];

            // Refresh Menu contents in case onCreateMenuOptions was called before Entry was set
            ActivityCompat.InvalidateOptionsMenu(this);

            // Update last access time.
            Entry.Touch(false);

            if (PwDefs.IsTanEntry(Entry) && prefs.GetBoolean(GetString(Resource.String.TanExpiresOnUse_key), Resources.GetBoolean(Resource.Boolean.TanExpiresOnUse_default)) && ((Entry.Expires == false) || Entry.ExpiryTime > DateTime.Now))
            {
                PwEntry backupEntry = Entry.CloneDeep();
                Entry.ExpiryTime = DateTime.Now;
                Entry.Expires    = true;
                Entry.Touch(true);
                RequiresRefresh();
                UpdateEntry  update = new UpdateEntry(this, App.Kp2a, backupEntry, Entry, null);
                ProgressTask pt     = new ProgressTask(App.Kp2a, this, update);
                pt.Run();
            }
            FillData();

            SetupEditButtons();

            App.Kp2a.GetDb().LastOpenedEntry = new PwEntryOutput(Entry, App.Kp2a.GetDb().KpDatabase);

            _pluginActionReceiver = new PluginActionReceiver(this);
            RegisterReceiver(_pluginActionReceiver, new IntentFilter(Strings.ActionAddEntryAction));
            _pluginFieldReceiver = new PluginFieldReceiver(this);
            RegisterReceiver(_pluginFieldReceiver, new IntentFilter(Strings.ActionSetEntryField));

            new Thread(NotifyPluginsOnOpen).Start();

            //the rest of the things to do depends on the current app task:
            _appTask.CompleteOnCreateEntryActivity(this);
        }
Пример #4
0
        private bool InitFingerprintUnlock()
        {
            Kp2aLog.Log("InitFingerprintUnlock");

            if (_fingerprintIdentifier != null)
            {
                Kp2aLog.Log("Already listening for fingerprint!");
                return(true);
            }


            var btn = FindViewById <ImageButton>(Resource.Id.fingerprintbtn);

            try
            {
                FingerprintUnlockMode um;
                Enum.TryParse(PreferenceManager.GetDefaultSharedPreferences(this).GetString(App.Kp2a.GetDb().CurrentFingerprintModePrefKey, ""), out um);
                btn.Visibility = (um != FingerprintUnlockMode.Disabled) ? ViewStates.Visible : ViewStates.Gone;

                if (um == FingerprintUnlockMode.Disabled)
                {
                    _fingerprintIdentifier = null;
                    return(false);
                }

                if (_fingerprintPermissionGranted)
                {
                    FingerprintModule fpModule = new FingerprintModule(this);
                    Kp2aLog.Log("fpModule.FingerprintManager.IsHardwareDetected=" + fpModule.FingerprintManager.IsHardwareDetected);
                    if (fpModule.FingerprintManager.IsHardwareDetected)                     //see FingerprintSetupActivity
                    {
                        _fingerprintIdentifier = new FingerprintDecryption(fpModule, App.Kp2a.GetDb().CurrentFingerprintPrefKey, this,
                                                                           App.Kp2a.GetDb().CurrentFingerprintPrefKey);
                    }
                }
                if ((_fingerprintIdentifier == null) && (!FingerprintDecryption.IsSetUp(this, App.Kp2a.GetDb().CurrentFingerprintPrefKey)))
                {
                    try
                    {
                        Kp2aLog.Log("trying Samsung Fingerprint API...");
                        _fingerprintIdentifier = new FingerprintSamsungIdentifier(this);
                        btn.Click += (sender, args) =>
                        {
                            if (_fingerprintIdentifier.Init())
                            {
                                _fingerprintIdentifier.StartListening(this, this);
                            }
                        };
                        Kp2aLog.Log("trying Samsung Fingerprint API...Seems to work!");
                    }
                    catch (Exception)
                    {
                        Kp2aLog.Log("trying Samsung Fingerprint API...failed.");
                        _fingerprintIdentifier = null;
                    }
                }
                if (_fingerprintIdentifier == null)
                {
                    FindViewById <ImageButton>(Resource.Id.fingerprintbtn).Visibility = ViewStates.Gone;
                    return(false);
                }
                btn.Tag = GetString(Resource.String.fingerprint_unlock_hint);

                if (_fingerprintIdentifier.Init())
                {
                    Kp2aLog.Log("successfully initialized fingerprint.");
                    btn.SetImageResource(Resource.Drawable.ic_fp_40px);
                    _fingerprintIdentifier.StartListening(this, this);
                    return(true);
                }
                else
                {
                    Kp2aLog.Log("failed to initialize fingerprint.");
                    HandleFingerprintKeyInvalidated();
                }
            }
            catch (Exception e)
            {
                Kp2aLog.Log("Error initializing Fingerprint Unlock: " + e);
                btn.SetImageResource(Resource.Drawable.ic_fingerprint_error);
                btn.Tag = "Error initializing Fingerprint Unlock: " + e;

                _fingerprintIdentifier = null;
            }
            return(false);
        }
Пример #5
0
        private bool AddOrUpdateValue(string key, object value, TypeCode typeCode)
        {
            lock (locker)
            {
                using (var sharedPreferences = PreferenceManager.GetDefaultSharedPreferences(Application.Context))
                {
                    using (var sharedPreferencesEditor = sharedPreferences.Edit())
                    {
                        switch (typeCode)
                        {
                        case TypeCode.Decimal:
                            sharedPreferencesEditor.PutString(key,
                                                              Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case TypeCode.Boolean:
                            sharedPreferencesEditor.PutBoolean(key, Convert.ToBoolean(value));
                            break;

                        case TypeCode.Int64:
                            sharedPreferencesEditor.PutLong(key,
                                                            (long)Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case TypeCode.String:
                            sharedPreferencesEditor.PutString(key, Convert.ToString(value));
                            break;

                        case TypeCode.Double:
                            sharedPreferencesEditor.PutString(key,
                                                              Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case TypeCode.Int32:
                            sharedPreferencesEditor.PutInt(key,
                                                           Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case TypeCode.Single:
                            sharedPreferencesEditor.PutFloat(key,
                                                             Convert.ToSingle(value, System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case TypeCode.DateTime:
                            sharedPreferencesEditor.PutLong(key, -(Convert.ToDateTime(value)).ToUniversalTime().Ticks);
                            break;

                        default:
                            if (value is Guid)
                            {
                                sharedPreferencesEditor.PutString(key, ((Guid)value).ToString());
                            }
                            else
                            {
                                throw new ArgumentException(string.Format("Value of type {0} is not supported.",
                                                                          value.GetType().Name));
                            }
                            break;
                        }

                        sharedPreferencesEditor.Commit();
                    }
                }
            }

            return(true);
        }
 private bool RememberRecentFiles()
 {
     return(PreferenceManager.GetDefaultSharedPreferences(this).GetBoolean(GetString(Resource.String.RememberRecentFiles_key), Resources.GetBoolean(Resource.Boolean.RememberRecentFiles_default)));
 }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            _activityDesign.ApplyTheme();
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.fingerprint_setup);

            Enum.TryParse(
                PreferenceManager.GetDefaultSharedPreferences(this).GetString(App.Kp2a.CurrentDb.CurrentFingerprintModePrefKey, ""),
                out _unlockMode);

            _fpIcon     = FindViewById <ImageView>(Resource.Id.fingerprint_icon);
            _fpTextView = FindViewById <TextView>(Resource.Id.fingerprint_status);

            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.SetHomeButtonEnabled(true);

            int[] radioButtonIds =
            {
                Resource.Id.radio_fingerprint_quickunlock, Resource.Id.radio_fingerprint_unlock,
                Resource.Id.radio_fingerprint_disabled
            };
            _radioButtons        = radioButtonIds.Select(FindViewById <RadioButton>).ToArray();
            _radioButtons[0].Tag = FingerprintUnlockMode.QuickUnlock.ToString();
            _radioButtons[1].Tag = FingerprintUnlockMode.FullUnlock.ToString();
            _radioButtons[2].Tag = FingerprintUnlockMode.Disabled.ToString();
            foreach (RadioButton r in _radioButtons)
            {
                r.CheckedChange += (sender, args) =>
                {
                    var rbSender = ((RadioButton)sender);
                    if (!rbSender.Checked)
                    {
                        return;
                    }
                    foreach (RadioButton rOther in _radioButtons)
                    {
                        if (rOther == sender)
                        {
                            continue;
                        }
                        rOther.Checked = false;
                    }
                    FingerprintUnlockMode newMode;
                    Enum.TryParse(rbSender.Tag.ToString(), out newMode);
                    ChangeUnlockMode(_unlockMode, newMode);
                };
            }

            CheckCurrentRadioButton();

            int errorId = Resource.String.fingerprint_os_error;

            SetError(errorId);

            FindViewById(Resource.Id.cancel_button).Click += (sender, args) =>
            {
                _enc.StopListening();
                _unlockMode = FingerprintUnlockMode.Disabled;                 //cancelling a FingerprintEncryption means a new key has been created but not been authenticated to encrypt something. We can't keep the previous state.
                StoreUnlockMode();
                FindViewById(Resource.Id.radio_buttons).Visibility = ViewStates.Visible;
                FindViewById(Resource.Id.fingerprint_auth_container).Visibility = ViewStates.Gone;
                _enc = null;
                CheckCurrentRadioButton();
            };

            FindViewById(Resource.Id.radio_buttons).Visibility = ViewStates.Gone;
            FindViewById(Resource.Id.fingerprint_auth_container).Visibility = ViewStates.Gone;
            FindViewById <CheckBox>(Resource.Id.show_keyboard_while_fingerprint).Checked =
                Util.GetShowKeyboardDuringFingerprintUnlock(this);

            FindViewById <CheckBox>(Resource.Id.show_keyboard_while_fingerprint).CheckedChange += (sender, args) =>
            {
                PreferenceManager.GetDefaultSharedPreferences(this)
                .Edit()
                .PutBoolean(GetString(Resource.String.ShowKeyboardWhileFingerprint_key), args.IsChecked)
                .Commit();
            };
            if ((int)Build.VERSION.SdkInt >= 23)
            {
                RequestPermissions(new[] { Manifest.Permission.UseFingerprint }, FingerprintPermissionRequestCode);
            }
            else
            {
                TrySetupSamsung();
            }

            UpdateKeyboardCheckboxVisibility();
        }
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            View view = convertView;

            view = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.ServicioDisponibleLayout, parent, false);

            var prod = servicios[position];
            var serviciodisponible = view.FindViewById <TextView>(Resource.Id.seriviciodisponible);
            var lugarrecolectad    = view.FindViewById <TextView>(Resource.Id.sitiorecolectadisponible);
            var hestimada          = view.FindViewById <TextView>(Resource.Id.horaestimadaserviciodisponible);
            var boton = view.FindViewById <Button>(Resource.Id.aceptarservicio);

            serviciodisponible.Text = prod.IdPedido;
            lugarrecolectad.Text    = prod.NombrePlaza;
            string   hora   = prod.HoraEstimada;
            DateTime hijole = Convert.ToDateTime(hora);
            int      x      = 45;
            DateTime puede  = hijole.AddMinutes(x);
            var      se     = puede.ToString("hh:mm");

            hestimada.Text = se;

            boton.Click += delegate {
                try
                {
                    ISharedPreferences preff = PreferenceManager.GetDefaultSharedPreferences(context);
                    var    id    = preff.GetString("Usuario", "");
                    var    name  = preff.GetString("NombreRepartidor", "");
                    var    phone = preff.GetString("TelefonoRepartidor", "");
                    string sql3  = string.Format("Select irrelevante from TapFood.Pedido where (IdPedido = '{0}' and Recolectada ='NO')", prod.IdPedido);
                    Console.WriteLine(sql3);
                    MySqlCommand    cty3 = new MySqlCommand(sql3, conn);
                    MySqlDataReader plz3;
                    plz3 = cty3.ExecuteReader();
                    List <int> irr = new List <int>();
                    while (plz3.Read())
                    {
                        int y;
                        y = (int)plz3["irrelevante"];
                        irr.Add(y);
                    }
                    plz3.Close();
                    Console.WriteLine(irr);
                    for (int i = 0; i < irr.Count; i++)
                    {
                        //int please = (int)plz3["Irrelevante"];
                        string rec  = "En proceso";
                        string sql4 = string.Format("UPDATE `TapFood`.`Pedido` SET `IdRepartidor` = '{0}', `NombreRepartidor` = '{1}', `TelefonoRepartidor` = '{2}', `Recolectada`='{3}' WHERE (`irrelevante` = '{4}')", id, name, phone, rec, irr.ElementAt(i).ToString());;
                        Console.WriteLine(sql4);
                        MySqlCommand cmd = new MySqlCommand(sql4, conn);
                        cmd.ExecuteNonQuery();
                    }
                }
                catch
                {
                    Toast.MakeText(context, "El servicio ya no esta disponible", ToastLength.Long).Show();
                }
            };

            return(view);
        }
        public override void OnFillRequest(FillRequest request, CancellationSignal cancellationSignal, FillCallback callback)
        {
            bool isManual = (request.Flags & FillRequest.FlagManualRequest) != 0;

            CommonUtil.logd("onFillRequest " + (isManual ? "manual" : "auto"));
            var structure = request.FillContexts.Last().Structure;


            if (_lockTime + _lockTimeout < DateTime.Now)
            {
                _lockTime = DateTime.Now;

                //TODO support package signature verification as soon as this is supported in Keepass storage

                var clientState = request.ClientState;
                CommonUtil.logd("onFillRequest(): data=" + CommonUtil.BundleToString(clientState));


                cancellationSignal.CancelEvent += (sender, e) =>
                {
                    Kp2aLog.Log("Cancel autofill not implemented yet.");
                    _lockTime = DateTime.MinValue;
                };
                // Parse AutoFill data in Activity
                StructureParser.AutofillTargetId query = null;
                var parser = new StructureParser(this, structure);
                try
                {
                    query = parser.ParseForFill(isManual);
                }
                catch (Java.Lang.SecurityException e)
                {
                    Log.Warn(CommonUtil.Tag, "Security exception handling request");
                    callback.OnFailure(e.Message);
                    return;
                }

                AutofillFieldMetadataCollection autofillFields = parser.AutofillFields;


                var autofillIds = autofillFields.GetAutofillIds();
                if (autofillIds.Length != 0 && CanAutofill(query, isManual))
                {
                    var responseBuilder = new FillResponse.Builder();

                    bool hasEntryDataset = false;

                    if (query.IncompatiblePackageAndDomain == false)
                    {
                        //domain and package are compatible. Use Domain if available and package otherwise. Can fill without warning.
                        foreach (var entryDataset in BuildEntryDatasets(query.DomainOrPackage, query.WebDomain,
                                                                        query.PackageName,
                                                                        autofillIds, parser, DisplayWarning.None).Where(ds => ds != null)
                                 )
                        {
                            responseBuilder.AddDataset(entryDataset);
                            hasEntryDataset = true;
                        }
                    }



                    {
                        if (query.WebDomain != null)
                        {
                            AddQueryDataset(query.WebDomain,
                                            query.WebDomain, query.PackageName,
                                            isManual, autofillIds, responseBuilder, !hasEntryDataset,
                                            query.IncompatiblePackageAndDomain
                                    ? DisplayWarning.FillDomainInUntrustedApp
                                    : DisplayWarning.None);
                        }
                        else
                        {
                            AddQueryDataset(query.PackageNameWithPseudoSchema,
                                            query.WebDomain, query.PackageName,
                                            isManual, autofillIds, responseBuilder, !hasEntryDataset, DisplayWarning.None);
                        }
                    }

                    AddDisableDataset(query.DomainOrPackage, autofillIds, responseBuilder, isManual);

                    if (PreferenceManager.GetDefaultSharedPreferences(this)
                        .GetBoolean(GetString(Resource.String.OfferSaveCredentials_key), true))
                    {
                        if (!CompatBrowsers.Contains(parser.PackageId))
                        {
                            responseBuilder.SetSaveInfo(new SaveInfo.Builder(parser.AutofillFields.SaveType,
                                                                             parser.AutofillFields.GetAutofillIds()).Build());
                        }
                    }

                    Kp2aLog.Log("return autofill success");
                    callback.OnSuccess(responseBuilder.Build());
                }
                else
                {
                    Kp2aLog.Log("cannot autofill");
                    callback.OnSuccess(null);
                }
            }
            else
            {
                Kp2aLog.Log("Ignoring onFillRequest as there is another request going on.");
            }
        }
Пример #10
0
        private string GetThemePreference()
        {
            var sharedPrefs = PreferenceManager.GetDefaultSharedPreferences(this);

            return(sharedPrefs.GetString("pref_theme", "0"));
        }
Пример #11
0
 public SharedPreferencesService()
 {
     _prefs  = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
     _editor = _prefs.Edit();
 }
Пример #12
0
        private async Task UpdateValues(NopCore api)
        {
            ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
            var PendingV             = FindViewById <TextView>(Resource.Id.pending);
            var CompleteV            = FindViewById <TextView>(Resource.Id.complete);
            var CancelledV           = FindViewById <TextView>(Resource.Id.cancelled);
            var PendingCountV        = FindViewById <TextView>(Resource.Id.pendingorders);
            var CartsCountV          = FindViewById <TextView>(Resource.Id.carts);
            var WishlistCountV       = FindViewById <TextView>(Resource.Id.wishlists);
            var RegisteredV          = FindViewById <TextView>(Resource.Id.registered);
            var OnlineV              = FindViewById <TextView>(Resource.Id.online);
            var VendorsV             = FindViewById <TextView>(Resource.Id.vendors);
            var BestsellerQV         = FindViewById <TextView>(Resource.Id.bestsellersquantity);
            var BestsellerAV         = FindViewById <TextView>(Resource.Id.bestsellersamount);
            var KeywordsLoadingV     = FindViewById <TextView>(Resource.Id.keywords);
            var KeywordsLayoutHolder = FindViewById <LinearLayout>(Resource.Id.wordlayout);

            var Complete = await api.GetStats(2);

            var Pending = await api.GetStats(3);

            var Cancelled = await api.GetStats(1);

            var Currency = await api.GetCurrency();

            if (prefs.GetString("sales_format", "Integer").Equals("Integer"))
            {
                PendingV.Text   = Pending.ToString("0") + " " + Currency;
                CompleteV.Text  = Complete.ToString("0") + " " + Currency;
                CancelledV.Text = Cancelled.ToString("0") + " " + Currency;
            }
            else
            {
                PendingV.Text   = Pending.ToString("0.0#") + " " + Currency;
                CompleteV.Text  = Complete.ToString("0.0#") + " " + Currency;
                CancelledV.Text = Cancelled.ToString("0.0#") + " " + Currency;
            }



            var PendingCount = await api.GetPendingOrdersCount();

            var CartsCount = await api.GetCartsCount();

            var WishlistCount = await api.GetWishlistCount();

            PendingCountV.Text  = PendingCount.ToString();
            CartsCountV.Text    = CartsCount.ToString();
            WishlistCountV.Text = WishlistCount.ToString();

            var Registered = await api.GetRegisteredCustomersCount();

            var Online = await api.GetOnlineCount();

            var Vendors = await api.GetVendorsCount();

            RegisteredV.Text = Registered.ToString();
            OnlineV.Text     = Online.ToString();
            VendorsV.Text    = Vendors.ToString();

            var Keywords = await api.GetPopularKeywords(3);

            var BestsellerQ = await api.GetBestsellerByQuantity();

            var BestsellerA = await api.GetBestsellerByAmount();

            int wordSpace = DensityPixel(2);

            KeywordsLayoutHolder.RemoveAllViews();
            for (int i = 0; i < prefs.GetInt("keywords_dashboard", 3); i++)
            {
                LinearLayout WordHolder = new LinearLayout(this);
                LinearLayout.LayoutParams WordLayout = (LinearLayout.LayoutParams)KeywordsLayoutHolder.LayoutParameters;
                WordHolder.Orientation = Orientation.Horizontal;
                var WHParams = WordLayout;
                WHParams.SetMargins(0, 0, wordSpace, 0);
                WordHolder.LayoutParameters = WHParams;
                TextView word = new TextView(this);
                word.Text = Keywords[i].Keyword;
                word.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.keyword_holder_bg));
                word.SetTextColor(Resources.GetColor(Resource.Color.white));
                word.SetPadding(wordSpace, wordSpace, wordSpace, wordSpace);
                word.SetSingleLine();
                WordHolder.AddView(word);
                KeywordsLayoutHolder.AddView(WordHolder);
            }

            BestsellerAV.Text = BestsellerA[0].Product.Name;
            BestsellerQV.Text = BestsellerQ[0].Product.Name;

            var WeekCustomers = await api.GetCustomerCountByTime(7);

            var TwoWeeksCustomers = await api.GetCustomerCountByTime(14);

            var MonthCustomers = await api.GetCustomerCountByTime(30);

            var YearCustomers = await api.GetCustomerCountByTime(365);

            var registered = new int [4] {
                WeekCustomers, TwoWeeksCustomers, MonthCustomers, YearCustomers
            };

            RegisteredUsersGraph Graph = new RegisteredUsersGraph(registered, false);
            var plotView = FindViewById <PlotView>(Resource.Id.plotView_Temp);

            plotView.Model = Graph.MyModel;

            dialog.Dismiss();
        }
Пример #13
0
        public override void OnReceive(Context context, Intent intent)
        {
            Log.Debug(nameof(ScreenUnlockReceiver), intent.Action);

            var notificationSender = new NotificationSender(context, DataHolder.ScreenLocksCategory);

            if (_mPreferences == null)
            {
                _mPreferences = PreferenceManager.GetDefaultSharedPreferences(context);
            }

            var now = new Date();

            long monitoringStartTime;

            if ((monitoringStartTime = _mPreferences.GetLong(ScreenUtils.MonitoringLastStartTime, -1)) == -1)
            {
                monitoringStartTime = ScreenUtils.GetMonitoringStartTime(now);
                _mPreferences.Edit().PutLong(ScreenUtils.MonitoringLastStartTime, monitoringStartTime).Apply();
                using (var writer = new StreamWriter(
                           context.OpenFileOutput(DebugFile, FileCreationMode.Append)))
                {
                    writer.WriteLine($"----Monitoring u start Time: {now.GetFormattedDateTime()}----");
                }
            }
            else
            {
                monitoringStartTime = ScreenUtils.GetMonitoringStartTime(new Date(monitoringStartTime));
            }

            if (_lastDayUnlocked == -1)
            {
                int tmpDay;
                if ((tmpDay = _mPreferences.GetInt(ScreenUtils.LastUnlockDay, -1)) != -1)
                {
                    _lastDayUnlocked = tmpDay;
                    UnlockedTimes    = _mPreferences.GetInt(ScreenUtils.UnlocksToday, 0);
                }
                else
                {
                    _lastDayUnlocked = Calendar.Instance.Get(CalendarField.DayOfWeek);
                    _mPreferences.Edit().PutInt(ScreenUtils.LastUnlockDay, _lastDayUnlocked).Apply();
                }
            }

            if (_unlockMillis == null)
            {
                var thisDay = _mPreferences.GetInt($"{ScreenUtils.UnlocksDayNumber}{_lastDayUnlocked}", 0);
                _todayNormalSpeedValue = Math.Max(
                    _abnormalUnlockMinCount,
                    (int)(thisDay * _abnormalUnlockPercentage / 100d));
                _unlockMillis = new List <long>();
            }

            if (TimeUnit.Milliseconds.ToDays(now.Time - monitoringStartTime) >= 1)
            {
                var unlocksToPut = UnlockedTimes;
                int u;

                if ((u = _mPreferences.GetInt($"{ScreenUtils.UnlocksDayNumber}{_lastDayUnlocked}", -1)) != -1)
                {
                    unlocksToPut = (int)Math.Ceiling((u + unlocksToPut) / 2d);
                }

                var tmpDay = _lastDayUnlocked;
                _lastDayUnlocked = Calendar.Instance.Get(CalendarField.DayOfWeek);
                UnlockedTimes    = 1;

                var thisDay = _mPreferences.GetInt($"{ScreenUtils.UnlocksDayNumber}{_lastDayUnlocked}", 0);
                _todayNormalSpeedValue = Math.Max(
                    _abnormalUnlockMinCount,
                    (int)(thisDay * _abnormalUnlockPercentage / 100d));
                _unlockMillis = new List <long>();

                _mPreferences.Edit()
                .PutInt($"{ScreenUtils.UnlocksDayNumber}{tmpDay}", unlocksToPut)
                .PutInt(ScreenUtils.LastUnlockDay, _lastDayUnlocked)
                .PutLong(ScreenUtils.MonitoringLastStartTime, ScreenUtils.GetMonitoringStartTime(now))
                .PutInt(ScreenUtils.UnlocksToday, UnlockedTimes)
                .PutInt(ScreenUtils.UnlocksNewNormalCount, -1)
                .Apply();

                MainActivity.Adapter?.Refresh();
                return;
            }

            Log.Debug("AbScreenReceiver",
                      $"Not new day. Was {new Date(monitoringStartTime).GetFormattedDateTime()}, now {now.GetFormattedDateTime()}");

            _mPreferences.Edit().PutInt(ScreenUtils.UnlocksToday, ++UnlockedTimes).Apply();

            var mode = 0;

            if (UnlockedTimes > GetNormalUnlocksCount(_mPreferences) * 1.1)
            {
                mode = 1;
            }

            _abnormalUnlockInterval = _mPreferences.GetInt(AbnormalUnlocksTimeInterval, _abnormalUnlockInterval);

            if (_unlockMillis.Count > _todayNormalSpeedValue)
            {
                var s = TimeUnit.Milliseconds.ToSeconds(now.Time - _unlockMillis[0]);

                if (s <= _abnormalUnlockInterval && s > 0)
                {
                    mode = 2;
                    using (var writer = new StreamWriter(
                               context.OpenFileOutput(DebugFile, FileCreationMode.Append)))
                    {
                        writer.WriteLine($"----Time: {new Date().GetFormattedDateTime()}----");
                        foreach (var unlock in _unlockMillis)
                        {
                            writer.WriteLine($"Unlock at {new Date(unlock).GetFormattedDateTime()}, val = {unlock}");
                        }

                        writer.WriteLine("-----End1-----");
                    }
                }
                else
                {
                    var  tmpList = new List <long>();
                    long sec;
                    foreach (var time in _unlockMillis)
                    {
                        sec = TimeUnit.Milliseconds.ToSeconds(now.Time - time);
                        if (sec <= _abnormalUnlockInterval && sec > 0)
                        {
                            tmpList.Add(time);
                        }
                    }

                    _unlockMillis = tmpList;
                    sec           = TimeUnit.Milliseconds.ToSeconds(now.Time - _unlockMillis[0]);
                    if (_unlockMillis.Count > _todayNormalSpeedValue && sec <= _abnormalUnlockInterval && sec > 0)
                    {
                        mode = 2;
                        using (var writer = new StreamWriter(
                                   context.OpenFileOutput(DebugFile, FileCreationMode.Append)))
                        {
                            writer.WriteLine($"----Time: {new Date().GetFormattedDateTime()}----");
                            foreach (var unlock in _unlockMillis)
                            {
                                writer.WriteLine(
                                    $"Unlock at {new Date(unlock).GetFormattedDateTime()}, val = {unlock}");
                            }

                            writer.WriteLine("-----End2-----");
                        }
                    }
                }
            }

            _unlockMillis.Add(now.Time);

            string notificationText;

            switch (mode)
            {
            case 1:
                Status           = ScreenStatus.Many;
                notificationText =
                    string.Format(context.GetString(Resource.String.category_screen_notif_daily_overflow),
                                  UnlockedTimes, NormalCount);
                notificationSender.PutNormalizeExtra(ScreenUtils.UnlocksNewNormalCount,
                                                     (int)(UnlockedTimes * 1.2));

                CategoriesAdapter.Refresh(DataHolder.ScreenCategory);
                break;

            case 2:
                var tmpInterval = (int)(.9 * _abnormalUnlockInterval);
                if (tmpInterval >= _abnormalUnlockInterval)
                {
                    if (tmpInterval > 1)
                    {
                        tmpInterval--;
                    }
                }

                Status           = ScreenStatus.Speed;
                notificationText =
                    string.Format(context.GetString(Resource.String.category_screen_notif_west_fast_hand),
                                  _unlockMillis.Count,
                                  TimeUnit.Milliseconds.ToSeconds(_unlockMillis.Last() - _unlockMillis.First()));

                notificationSender.PutNormalizeExtra(AbnormalUnlocksTimeInterval, tmpInterval);
                CategoriesAdapter.Refresh(DataHolder.ScreenCategory);
                break;

            default:
                Status = ScreenStatus.OK;
                CategoriesAdapter.Refresh(DataHolder.ScreenCategory);
                return;
            }

            using (var writer =
                       new StreamWriter(context.OpenFileOutput(AlarmReceiver.CurrentSummaryFile, FileCreationMode.Append)))
            {
                writer.WriteLine(notificationText);
            }

            notificationSender.Send(NotificationType.WarningNotification, notificationText);
        }
Пример #14
0
        public static float GetListTextSize(Context ctx)
        {
            ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(ctx);

            return(float.Parse(prefs.GetString(ctx.GetString(Resource.String.list_size_key), ctx.GetString(Resource.String.list_size_default))));
        }
        /// <summary>
        /// Called when the activity is starting.
        /// </summary>
        /// <param name="savedInstanceState">
        /// If the activity is being re-initialized after previously being shut down then
        /// this <see cref="Bundle"/> contains the data it most recently supplied in
        /// <see cref="Android.App.Activity.OnSaveInstanceState(Android.OS.Bundle)"/>.
        /// Note: Otherwise it is <b>null</b>.
        /// </param>
        protected override void OnCreate(Bundle savedInstanceState)
        {
            // subscribe to the unhandled exception events
            AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;
            AppDomain.CurrentDomain.UnhandledException  += CurrentDomain_UnhandledException;

            base.OnCreate(savedInstanceState);

            // add "fullscreen" window flag
            Window.AddFlags(WindowManagerFlags.Fullscreen);

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

            try
            {
                // set the default values from an XML preference file
                PreferenceManager.SetDefaultValues(this, Resource.Xml.settings_page, false);

                // get preferences
                ISharedPreferences preferences = PreferenceManager.GetDefaultSharedPreferences(this);
                // get the language name
                string languageToLoad = preferences.GetString("list_languages", "auto");
                // if language name is not auto
                if (languageToLoad != "auto")
                {
                    // set choosen locale
                    Locale locale = new Locale(languageToLoad);
                    Locale.Default = locale;
                    Configuration config = new Configuration();
                    config.Locale = locale;
                    BaseContext.Resources.UpdateConfiguration(config, BaseContext.Resources.DisplayMetrics);

                    this.SetContentView(Resource.Layout.main);
                }
            }
            catch
            {
            }

            SupportActionBar.SetHomeButtonEnabled(false);
            SupportActionBar.SetDisplayHomeAsUpEnabled(false);

            // check licence
            CheckLicense();

            // if Android version is equal or higher than 6.0 (API 23)
            if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                if (CheckSelfPermission(Android.Manifest.Permission.Camera) != Permission.Granted ||
                    CheckSelfPermission(Android.Manifest.Permission.Flashlight) != Permission.Granted ||
                    CheckSelfPermission(Android.Manifest.Permission.Vibrate) != Permission.Granted)
                {
                    RequestPermissions(
                        new string[] { Android.Manifest.Permission.Camera, Android.Manifest.Permission.Flashlight, Android.Manifest.Permission.Vibrate },
                        PERMISSION_REQUEST_CODE);
                }
                else
                {
                    _isCameraPermissionGranted = true;

                    // create fragments
                    _barcodeScannerFragment = new BarcodeScannerFragment(this, RecognizedBarcodes, true, true);
                    _historyFragment        = new HistoryFragment(this);
                    _settingsFragment       = new SettingsFragment(this);

                    // show barcode scanner fragment
                    SwitchToBarcodeScanner(null);
                }
            }
            // if Android version is less than 6.0 (API 23)
            else
            {
                _isCameraPermissionGranted = true;

                // create fragments
                _barcodeScannerFragment = new BarcodeScannerFragment(this, RecognizedBarcodes, true, true);
                _historyFragment        = new HistoryFragment(this);
                _settingsFragment       = new SettingsFragment(this);

                // show barcode scanner fragment
                SwitchToBarcodeScanner(null);
            }
        }
Пример #16
0
 public bool OnScaleBegin(ScaleGestureDetector detector)
 {
     sharedPrefs  = PreferenceManager.GetDefaultSharedPreferences(mContext);
     initTextSize = sharedPrefs.GetInt("pref_textSizeInt", 16);
     return(true);
 }
Пример #17
0
 private bool IsSmartShortcutsActivated()
 {
     return(PreferenceManager.GetDefaultSharedPreferences(context).GetBoolean(GetString(Resource.String.pref_smart_shortcuts_key), true));
 }
Пример #18
0
        public void onCustomClicked(View view)
        {
            var editor = PreferenceManager.GetDefaultSharedPreferences(this).Edit();

            editor.PutBoolean(CUSTOM_CONFIG_KEY, mCustomConfig.Checked).Apply();
        }
Пример #19
0
        public void DisplayAccessNotifications(PwEntryOutput entry, bool activateKeyboard, string searchUrl)
        {
            var hadKeyboardData = ClearNotifications();

            String   entryName = entry.OutputStrings.ReadSafe(PwDefs.TitleField);
            Database db        = App.Kp2a.FindDatabaseForElement(entry.Entry);

            var bmp = Util.DrawableToBitmap(db.DrawableFactory.GetIconDrawable(this,
                                                                               db.KpDatabase, entry.Entry.IconId, entry.Entry.CustomIconUuid, false));


            if (!(((entry.Entry.CustomIconUuid != null) && (!entry.Entry.CustomIconUuid.Equals(PwUuid.Zero)))) &&
                PreferenceManager.GetDefaultSharedPreferences(this).GetString("IconSetKey", PackageName) == PackageName)
            {
                Color drawingColor = new Color(189, 189, 189);
                bmp = Util.ChangeImageColor(bmp, drawingColor);
            }

            Bitmap entryIcon = Util.MakeLargeIcon(bmp, this);

            ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
            var notBuilder           = new PasswordAccessNotificationBuilder(this, _notificationManager);

            if (prefs.GetBoolean(GetString(Resource.String.CopyToClipboardNotification_key), Resources.GetBoolean(Resource.Boolean.CopyToClipboardNotification_default)))
            {
                if (entry.OutputStrings.ReadSafe(PwDefs.PasswordField).Length > 0)
                {
                    notBuilder.AddPasswordAccess();
                }

                if (entry.OutputStrings.ReadSafe(PwDefs.UserNameField).Length > 0)
                {
                    notBuilder.AddUsernameAccess();
                }
                if (entry.OutputStrings.ReadSafe(UpdateTotpTimerTask.TotpKey).Length > 0)
                {
                    notBuilder.AddTotpAccess();
                }
            }

            bool hasKeyboardDataNow = false;

            if (prefs.GetBoolean(GetString(Resource.String.UseKp2aKeyboard_key), Resources.GetBoolean(Resource.Boolean.UseKp2aKeyboard_default)))
            {
                //keyboard
                hasKeyboardDataNow = MakeAccessibleForKeyboard(entry, searchUrl);
                if (hasKeyboardDataNow)
                {
                    notBuilder.AddKeyboardAccess();
                    if (prefs.GetBoolean("kp2a_switch_rooted", false))
                    {
                        //switch rooted
                        bool onlySwitchOnSearch = prefs.GetBoolean(GetString(Resource.String.OpenKp2aKeyboardAutomaticallyOnlyAfterSearch_key), false);
                        if (activateKeyboard || (!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 ((activateKeyboard) && prefs.GetBoolean(GetString(Resource.String.OpenKp2aKeyboardAutomatically_key), Resources.GetBoolean(Resource.Boolean.OpenKp2aKeyboardAutomatically_default)))
                        {
                            ActivateKp2aKeyboard();
                        }
                    }
                }
            }

            if ((!hasKeyboardDataNow) && (hadKeyboardData))
            {
                ClearKeyboard(true); //this clears again and then (this is the point) broadcasts that we no longer have keyboard data
            }
            _numElementsToWaitFor = notBuilder.CreateNotifications(entryName, entryIcon);

            if (_numElementsToWaitFor == 0)
            {
                Kp2aLog.Log("Stopping CopyToClipboardService, created empty notification");
                StopSelf();
                return;
            }

            //register receiver to get notified when notifications are discarded in which case we can shutdown the service
            _notificationDeletedBroadcastReceiver = new NotificationDeletedBroadcastReceiver(this);
            IntentFilter deletefilter = new IntentFilter();

            deletefilter.AddAction(ActionNotificationCancelled);
            RegisterReceiver(_notificationDeletedBroadcastReceiver, deletefilter);
        }
Пример #20
0
        protected override void OnResume()
        {
            base.OnResume();

            //Set the IPAdress based on the gateway
            var liveService = this.ServiceManager.GetService(ServiceType.Live) as LiveService;

            liveService.Connection.IPAddress = GetIPAdress();

            ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);

            if (prefs.GetBoolean("DEMO", true))
            {
                this.ServiceManager.ServiceType = ServiceType.Demo;
                RunOnUiThread(() => { AlertUser("Demo Mode", "Demo mode is now running"); });
            }
            else
            {
                this.ServiceManager.ServiceType = ServiceType.Live;
                if (!Service.Active)
                {
                    if (!Service.Activate())
                    {
                        this.ServiceManager.ServiceType = ServiceType.Demo;
                        Service.Activate();
                        RunOnUiThread(() => { AlertUser("No Connection", "No WFS210 found\r\nDemo mode is now running"); });
                        var editor = prefs.Edit();
                        editor.PutBoolean("DEMO", true);
                        editor.Commit();
                    }
                    else
                    {
                        Service.RequestWifiSettings();
                        Service.RequestSettings();
                        Service.RequestSamples();
                    }
                }
            }

            if (prefs.GetBoolean("CALIBRATE", false))
            {
                Service.RequestCalibration();
                var editor = prefs.Edit();
                editor.PutBoolean("CALIBRATE", false);
                editor.Apply();
            }

            _ScopeView.DrawMarkers = prefs.GetBoolean("MARKERS", true);

            _UpdateTimer          = new Timer(200);
            _UpdateTimer.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) => {
                _UpdateTimer.Stop();
                Service.Update();
                RunOnUiThread(() => _ScopeView.Update());
                _UpdateTimer.Start();
            };
            _UpdateTimer.Enabled = true;
            _UpdateTimer.Start();

            UpdateScopeControls();
        }
Пример #21
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            _design.ApplyTheme();
            base.OnCreate(savedInstanceState);

            Android.Util.Log.Debug("KP2A", "Creating GBA");

            AppTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);

            // Likely the app has been killed exit the activity
            if (!App.Kp2a.GetDb().Loaded)
            {
                Finish();
                return;
            }

            _prefs = PreferenceManager.GetDefaultSharedPreferences(this);


            SetContentView(ContentResourceId);

            if (FindViewById(Resource.Id.enable_autofill) != null)
            {
                FindViewById(Resource.Id.enable_autofill).Click += (sender, args) =>
                {
                    var intent = new Intent(Settings.ActionRequestSetAutofillService);
                    intent.SetData(Android.Net.Uri.Parse("package:" + PackageName));
                    try
                    {
                        StartActivity(intent);
                    }
                    catch (ActivityNotFoundException e)
                    {
                        //this exception was reported by many Huawei users
                        Kp2aLog.LogUnexpectedError(e);
                        new AlertDialog.Builder(this)
                        .SetTitle(Resource.String.autofill_enable)
                        .SetMessage(Resource.String.autofill_enable_failed)
                        .SetPositiveButton(Resource.String.ok, (o, eventArgs) => { })
                        .Show();
                        const string autofillservicewasenabled = "AutofillServiceWasEnabled";
                        _prefs.Edit().PutBoolean(autofillservicewasenabled, true).Commit();
                        UpdateBottomBarElementVisibility(Resource.Id.autofill_infotext, false);
                    }
                };
            }

            if (FindViewById(Resource.Id.fabCancelAddNew) != null)
            {
                FindViewById(Resource.Id.fabAddNew).Click += (sender, args) =>
                {
                    FindViewById(Resource.Id.fabCancelAddNew).Visibility = ViewStates.Visible;
                    FindViewById(Resource.Id.fabAddNewGroup).Visibility  = AddGroupEnabled ? ViewStates.Visible : ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewEntry).Visibility  = AddEntryEnabled ? ViewStates.Visible : ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNew).Visibility       = ViewStates.Gone;
                };

                FindViewById(Resource.Id.fabCancelAddNew).Click += (sender, args) =>
                {
                    FindViewById(Resource.Id.fabCancelAddNew).Visibility = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewGroup).Visibility  = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNewEntry).Visibility  = ViewStates.Gone;
                    FindViewById(Resource.Id.fabAddNew).Visibility       = ViewStates.Visible;
                };
            }


            if (FindViewById(Resource.Id.cancel_insert_element) != null)
            {
                FindViewById(Resource.Id.cancel_insert_element).Click += (sender, args) => StopMovingElements();
                FindViewById(Resource.Id.insert_element).Click        += (sender, args) => InsertElements();
                Util.MoveBottomBarButtons(Resource.Id.cancel_insert_element, Resource.Id.insert_element, Resource.Id.bottom_bar, this);
            }

            if (FindViewById(Resource.Id.show_autofill_info) != null)
            {
                FindViewById(Resource.Id.show_autofill_info).Click += (sender, args) => Util.GotoUrl(this, "https://philippc.github.io/keepass2android/OreoAutoFill.html");
                Util.MoveBottomBarButtons(Resource.Id.show_autofill_info, Resource.Id.enable_autofill, Resource.Id.autofill_buttons, this);
            }

            if (FindViewById(Resource.Id.configure_notification_channels) != null)
            {
                FindViewById(Resource.Id.configure_notification_channels).Click += (sender, args) =>
                {
                    Intent intent = new Intent(Settings.ActionChannelNotificationSettings);
                    intent.PutExtra(Settings.ExtraChannelId, App.NotificationChannelIdQuicklocked);
                    intent.PutExtra(Settings.ExtraAppPackage, PackageName);
                    try
                    {
                        StartActivity(intent);
                    }
                    catch (Exception e)
                    {
                        new AlertDialog.Builder(this)
                        .SetTitle("Unexpected error")
                        .SetMessage(
                            "Opening the settings failed. Please report this to [email protected] including information about your device vendor and OS. Please try to configure the notifications by long pressing a KP2A notification. Details: " + e.ToString())
                        .Show();
                    }
                    UpdateAndroid8NotificationInfo(true);
                };
                FindViewById(Resource.Id.ignore_notification_channel).Click += (sender, args) =>
                {
                    UpdateAndroid8NotificationInfo(true);
                };
            }



            string lastInfoText;

            if (IsTimeForInfotext(out lastInfoText))
            {
                FingerprintUnlockMode um;
                Enum.TryParse(_prefs.GetString(Database.GetFingerprintModePrefKey(App.Kp2a.GetDb().Ioc), ""), out um);
                bool isFingerprintEnabled = (um == FingerprintUnlockMode.FullUnlock);

                string masterKeyKey = "MasterKey" + isFingerprintEnabled;
                string emergencyKey = "Emergency";
                string backupKey    = "Backup";

                List <string> applicableInfoTextKeys = new List <string> {
                    masterKeyKey
                };

                if (App.Kp2a.GetFileStorage(App.Kp2a.GetDb().Ioc).UserShouldBackup)
                {
                    applicableInfoTextKeys.Add(backupKey);
                }
                if (App.Kp2a.GetDb().Entries.Count > 15)
                {
                    applicableInfoTextKeys.Add(emergencyKey);
                }

                List <string> enabledInfoTextKeys = new List <string>();
                foreach (string key in applicableInfoTextKeys)
                {
                    if (!InfoTextWasDisabled(key))
                    {
                        enabledInfoTextKeys.Add(key);
                    }
                }

                if (enabledInfoTextKeys.Any())
                {
                    string infoTextKey = "", infoHead = "", infoMain = "", infoNote = "";

                    if (enabledInfoTextKeys.Count > 1)
                    {
                        foreach (string key in enabledInfoTextKeys)
                        {
                            if (key == lastInfoText)
                            {
                                enabledInfoTextKeys.Remove(key);
                                break;
                            }
                        }
                        infoTextKey = enabledInfoTextKeys[new Random().Next(enabledInfoTextKeys.Count)];
                    }

                    if (infoTextKey == masterKeyKey)
                    {
                        infoHead = GetString(Resource.String.masterkey_infotext_head);
                        infoMain = GetString(Resource.String.masterkey_infotext_main);
                        if (isFingerprintEnabled)
                        {
                            infoNote = GetString(Resource.String.masterkey_infotext_fingerprint_note);
                        }
                    }
                    else if (infoTextKey == emergencyKey)
                    {
                        infoHead = GetString(Resource.String.emergency_infotext_head);
                        infoMain = GetString(Resource.String.emergency_infotext_main);
                    }
                    else if (infoTextKey == backupKey)
                    {
                        infoHead = GetString(Resource.String.backup_infotext_head);
                        infoMain = GetString(Resource.String.backup_infotext_main);
                        infoNote = GetString(Resource.String.backup_infotext_note, GetString(Resource.String.menu_app_settings), GetString(Resource.String.menu_db_settings), GetString(Resource.String.export_prefs));
                    }



                    FindViewById <TextView>(Resource.Id.info_head).Text = infoHead;
                    FindViewById <TextView>(Resource.Id.info_main).Text = infoMain;
                    var additionalInfoText = FindViewById <TextView>(Resource.Id.info_additional);
                    additionalInfoText.Text       = infoNote;
                    additionalInfoText.Visibility = string.IsNullOrEmpty(infoNote) ? ViewStates.Gone : ViewStates.Visible;

                    if (infoTextKey != "")
                    {
                        RegisterInfoTextDisplay(infoTextKey);
                        FindViewById(Resource.Id.info_ok).Click += (sender, args) =>
                        {
                            UpdateBottomBarElementVisibility(Resource.Id.infotext, false);
                        };
                        FindViewById(Resource.Id.info_dont_show_again).Click += (sender, args) =>
                        {
                            UpdateBottomBarElementVisibility(Resource.Id.infotext, false);
                            DisableInfoTextDisplay(infoTextKey);
                        };

                        UpdateBottomBarElementVisibility(Resource.Id.infotext, true);
                    }
                }
            }



            SetResult(KeePass.ExitNormal);
        }
Пример #22
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            view   = inflater.Inflate(Resource.Layout.fragment_nohin_kaisyu_matehan, container, false);
            prefs  = PreferenceManager.GetDefaultSharedPreferences(Context);
            editor = prefs.Edit();

            // DB helper
            nohinMateHelper = new SndNohinMateHelper();
            mateFileHelper  = new MateFileHelper();

            // コンポーネント初期化
            SetTitle("マテハン回収");
            SetFooterText("");

            _VendorNameTextView = view.FindViewById <TextView>(Resource.Id.txt_nohinKaisyuMatehan_vendorName);
            matehan1Nm          = view.FindViewById <TextView>(Resource.Id.txt_nohinKaisyuMatehan_matehan1);
            matehan2Nm          = view.FindViewById <TextView>(Resource.Id.txt_nohinKaisyuMatehan_matehan2);
            matehan3Nm          = view.FindViewById <TextView>(Resource.Id.txt_nohinKaisyuMatehan_matehan3);
            matehan4Nm          = view.FindViewById <TextView>(Resource.Id.txt_nohinKaisyuMatehan_matehan4);

            matehan1Su = view.FindViewById <BootstrapEditText>(Resource.Id.et_nohinKaisyuMatehan_matehan1);
            matehan2Su = view.FindViewById <BootstrapEditText>(Resource.Id.et_nohinKaisyuMatehan_matehan2);
            matehan3Su = view.FindViewById <BootstrapEditText>(Resource.Id.et_nohinKaisyuMatehan_matehan3);
            matehan4Su = view.FindViewById <BootstrapEditText>(Resource.Id.et_nohinKaisyuMatehan_matehan4);

            BootstrapButton _ConfirmButton = view.FindViewById <BootstrapButton>(Resource.Id.btn_nohinKaisyuMatehan_confirm);

            _ConfirmButton.Click += delegate { ConfirmMatehanKaisyu(); };

            BootstrapButton _VendorSearchButton = view.FindViewById <BootstrapButton>(Resource.Id.vendorSearch);

            _VendorSearchButton.Click += delegate {
                editor.PutBoolean("kounaiFlag", false);
                editor.Apply();
                StartFragment(FragmentManager, typeof(KosuVendorAllSearchFragment));
            };

            _VendorCdEditText           = view.FindViewById <BootstrapEditText>(Resource.Id.et_nohinKaisyuMatehan_vendorCode);
            _VendorCdEditText.KeyPress += (sender, e) => {
                if (e.Event.Action == KeyEventActions.Down && e.KeyCode == Keycode.Enter)
                {
                    e.Handled = true;

                    matehanList = mateFileHelper.SelectByVendorCd(_VendorCdEditText.Text);

                    if (matehanList.Count == 0)
                    {
                        ShowDialog("エラー", "ベンダーコードが存在しません。", () => { _VendorCdEditText.Text = motoVendorCd; _VendorCdEditText.RequestFocus(); });
                        return;
                    }
                    else
                    {
                        SetMateVendorInfo(_VendorCdEditText.Text);
                        motoVendorCd             = _VendorCdEditText.Text;
                        _VendorNameTextView.Text = matehanList[0].vendor_nm;

                        editor.PutString("mate_vendor_cd", _VendorCdEditText.Text);
                        editor.PutString("mate_vendor_nm", matehanList[0].vendor_nm);
                        editor.Apply();
                    }
                }
                else
                {
                    e.Handled = false;
                }
            };

            return(view);
        }
Пример #23
0
        protected override void OnCreate(Bundle bundle)
        {
            _design.ApplyTheme();
            base.OnCreate(bundle);

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

            _ioc = App.Kp2a.GetDb().Ioc;

            if (_ioc == null)
            {
                Finish();
                return;
            }

            SetContentView(Resource.Layout.QuickUnlock);

            var toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.mytoolbar);

            SetSupportActionBar(toolbar);

            var collapsingToolbar = FindViewById <CollapsingToolbarLayout>(Resource.Id.collapsing_toolbar);

            collapsingToolbar.SetTitle(GetString(Resource.String.QuickUnlock_prefs));

            if (App.Kp2a.GetDb().KpDatabase.Name != "")
            {
                FindViewById(Resource.Id.filename_label).Visibility       = ViewStates.Visible;
                ((TextView)FindViewById(Resource.Id.filename_label)).Text = App.Kp2a.GetDb().KpDatabase.Name;
            }
            else
            {
                if (
                    PreferenceManager.GetDefaultSharedPreferences(this)
                    .GetBoolean(GetString(Resource.String.RememberRecentFiles_key),
                                Resources.GetBoolean(Resource.Boolean.RememberRecentFiles_default)))
                {
                    ((TextView)FindViewById(Resource.Id.filename_label)).Text = App.Kp2a.GetFileStorage(_ioc).GetDisplayName(_ioc);
                }
                else
                {
                    ((TextView)FindViewById(Resource.Id.filename_label)).Text = "*****";
                }
            }


            TextView txtLabel = (TextView)FindViewById(Resource.Id.QuickUnlock_label);

            _quickUnlockLength = App.Kp2a.QuickUnlockKeyLength;

            if (PreferenceManager.GetDefaultSharedPreferences(this)
                .GetBoolean(GetString(Resource.String.QuickUnlockHideLength_key), false))
            {
                txtLabel.Text = GetString(Resource.String.QuickUnlock_label_secure);
            }
            else
            {
                txtLabel.Text = GetString(Resource.String.QuickUnlock_label, new Java.Lang.Object[] { _quickUnlockLength });
            }


            EditText pwd = (EditText)FindViewById(Resource.Id.QuickUnlock_password);

            pwd.SetEms(_quickUnlockLength);
            Util.MoveBottomBarButtons(Resource.Id.QuickUnlock_buttonLock, Resource.Id.QuickUnlock_button, Resource.Id.bottom_bar, this);

            Button btnUnlock = (Button)FindViewById(Resource.Id.QuickUnlock_button);

            btnUnlock.Click += (object sender, EventArgs e) =>
            {
                OnUnlock(_quickUnlockLength, pwd);
            };



            Button btnLock = (Button)FindViewById(Resource.Id.QuickUnlock_buttonLock);

            btnLock.Text   = btnLock.Text.Replace("ß", "ss");
            btnLock.Click += (object sender, EventArgs e) =>
            {
                App.Kp2a.LockDatabase(false);
                Finish();
            };
            pwd.EditorAction += (sender, args) =>
            {
                if ((args.ActionId == ImeAction.Done) || ((args.ActionId == ImeAction.ImeNull) && (args.Event.Action == KeyEventActions.Down)))
                {
                    OnUnlock(_quickUnlockLength, pwd);
                }
            };

            _intentReceiver = new QuickUnlockBroadcastReceiver(this);
            IntentFilter filter = new IntentFilter();

            filter.AddAction(Intents.DatabaseLocked);
            RegisterReceiver(_intentReceiver, filter);

            if ((int)Build.VERSION.SdkInt >= 23)
            {
                Kp2aLog.Log("requesting fingerprint permission");
                RequestPermissions(new[] { Manifest.Permission.UseFingerprint }, FingerprintPermissionRequestCode);
            }
            else
            {
            }
        }
Пример #24
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);
            View view = inflater.Inflate(Resource.Layout.setting_fragment, container, false);

            checkBoxPA720    = view.FindViewById <CheckBox>(Resource.Id.checkBoxPA720);
            checkBoxTB120    = view.FindViewById <CheckBox>(Resource.Id.checkBoxTB120);
            checkBoxTestPort = view.FindViewById <CheckBox>(Resource.Id.checkBoxTestPort);
            checkBoxRealPort = view.FindViewById <CheckBox>(Resource.Id.checkBoxRealPort);

            //get default
            prefs = PreferenceManager.GetDefaultSharedPreferences(context);
            //pda type
            int pda_type = prefs.GetInt("PDA_TYPE", 0);
            //default port
            string web_soap_port = prefs.GetString("WEB_SOAP_PORT", "8484");

            if (pda_type == 0)
            {
                checkBoxPA720.Checked = true;
                checkBoxTB120.Checked = false;
            }
            else
            {
                checkBoxPA720.Checked = false;
                checkBoxTB120.Checked = true;
            }

            if (web_soap_port.Equals("8484"))
            {
                checkBoxTestPort.Checked = true;
                checkBoxRealPort.Checked = false;
            }
            else
            { //port 8000
                checkBoxTestPort.Checked = false;
                checkBoxRealPort.Checked = true;
            }

            checkBoxPA720.Click += (sender, e) =>
            {
                Intent settingIntent;
                if (checkBoxPA720.Checked)
                {
                    checkBoxTB120.Checked = false;

                    settingIntent = new Intent(Constants.ACTION_SETTING_PDA_TYPE_ACTION);
                    settingIntent.PutExtra("MODEL_TYPE", "0");
                }
                else
                {
                    checkBoxTB120.Checked = true;

                    settingIntent = new Intent(Constants.ACTION_SETTING_PDA_TYPE_ACTION);
                    settingIntent.PutExtra("MODEL_TYPE", "1");
                }
                context.SendBroadcast(settingIntent);
            };

            checkBoxTB120.Click += (sender, e) =>
            {
                Intent settingIntent;
                if (checkBoxTB120.Checked)
                {
                    checkBoxPA720.Checked = false;

                    settingIntent = new Intent(Constants.ACTION_SETTING_PDA_TYPE_ACTION);
                    settingIntent.PutExtra("MODEL_TYPE", "1");
                }
                else
                {
                    checkBoxPA720.Checked = true;

                    settingIntent = new Intent(Constants.ACTION_SETTING_PDA_TYPE_ACTION);
                    settingIntent.PutExtra("MODEL_TYPE", "0");
                }
                context.SendBroadcast(settingIntent);
            };

            checkBoxTestPort.Click += (sender, e) =>
            {
                Intent settingIntent;
                if (checkBoxTestPort.Checked)
                {
                    checkBoxRealPort.Checked = false;

                    settingIntent = new Intent(Constants.ACTION_SETTING_WEB_SOAP_PORT_ACTION);
                    settingIntent.PutExtra("WEB_SOAP_PORT", "8484");
                }
                else
                {
                    checkBoxRealPort.Checked = true;

                    settingIntent = new Intent(Constants.ACTION_SETTING_WEB_SOAP_PORT_ACTION);
                    settingIntent.PutExtra("WEB_SOAP_PORT", "8000");
                }
                context.SendBroadcast(settingIntent);
            };

            checkBoxRealPort.Click += (sender, e) =>
            {
                Intent settingIntent;
                if (checkBoxRealPort.Checked)
                {
                    checkBoxTestPort.Checked = false;

                    settingIntent = new Intent(Constants.ACTION_SETTING_WEB_SOAP_PORT_ACTION);
                    settingIntent.PutExtra("WEB_SOAP_PORT", "8000");
                }
                else
                {
                    checkBoxTestPort.Checked = true;

                    settingIntent = new Intent(Constants.ACTION_SETTING_WEB_SOAP_PORT_ACTION);
                    settingIntent.PutExtra("WEB_SOAP_PORT", "8484");
                }
                context.SendBroadcast(settingIntent);
            };

            return(view);
        }
Пример #25
0
 ISharedPreferences GetSharedPreference()
 {
     return(PreferenceManager.GetDefaultSharedPreferences(Application.Context));
 }
Пример #26
0
 /// <summary>
 /// Initializes a new instance of the AppPrefManager class.
 /// </summary>
 /// <param name="context">Context.</param>
 public AppPrefManager(Context context)
 {
     preferences = PreferenceManager.GetDefaultSharedPreferences(context);
 }
Пример #27
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            OnImagePicked += (sender, image) =>
            {
                if (image == null)
                {
                    return;
                }

                AppPreference appPreference = new AppPreference();
                CvInvoke.UseOpenCL = appPreference.UseOpenCL;
                String oclDeviceName = appPreference.OpenClDeviceName;
                if (!String.IsNullOrEmpty(oclDeviceName))
                {
                    CvInvoke.OclSetDefaultDevice(oclDeviceName);
                }


                ISharedPreferences preference = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext);
                String             appVersion = PackageManager.GetPackageInfo(PackageName, Android.Content.PM.PackageInfoFlags.Activities).VersionName;
                if (!preference.Contains("cascade-data-version") || !preference.GetString("cascade-data-version", null).Equals(appVersion) ||
                    !(preference.Contains("cascade-eye-data-path") || preference.Contains("cascade-face-data-path")))
                {
                    AndroidFileAsset.OverwriteMethod overwriteMethod = AndroidFileAsset.OverwriteMethod.AlwaysOverwrite;

                    FileInfo eyeFile  = AndroidFileAsset.WritePermanantFileAsset(this, "haarcascade_eye.xml", "cascade", overwriteMethod);
                    FileInfo faceFile = AndroidFileAsset.WritePermanantFileAsset(this, "haarcascade_frontalface_default.xml", "cascade", overwriteMethod);

                    //save tesseract data path
                    ISharedPreferencesEditor editor = preference.Edit();
                    editor.PutString("cascade-data-version", appVersion);
                    editor.PutString("cascade-eye-data-path", eyeFile.FullName);
                    editor.PutString("cascade-face-data-path", faceFile.FullName);
                    editor.Commit();
                }

                string           eyeXml  = preference.GetString("cascade-eye-data-path", null);
                string           faceXml = preference.GetString("cascade-face-data-path", null);
                long             time;
                List <Rectangle> faces = new List <Rectangle>();
                List <Rectangle> eyes  = new List <Rectangle>();


                DetectFace.Detect(image, faceXml, eyeXml, faces, eyes, out time);

                String computeDevice = CvInvoke.UseOpenCL ? "OpenCL: " + Emgu.CV.Ocl.Device.Default.Name : "CPU";
                SetMessage(String.Format("Detected with {1} in {0} milliseconds.", time, computeDevice));

                foreach (Rectangle rect in faces)
                {
                    CvInvoke.Rectangle(image, rect, new Bgr(System.Drawing.Color.Red).MCvScalar, 2);
                }

                foreach (Rectangle rect in eyes)
                {
                    CvInvoke.Rectangle(image, rect, new Bgr(System.Drawing.Color.Blue).MCvScalar, 2);
                }

                SetImageBitmap(image.ToBitmap());
                image.Dispose();

                if (CvInvoke.UseOpenCL)
                {
                    CvInvoke.OclFinish();
                }
            };

            OnButtonClick += (sender, args) =>
            {
                PickImage("lena.jpg");
            };
        }
Пример #28
0
 public AppPreferences()
 {
     sharedPrefs = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
     prefsEditor = sharedPrefs.Edit();
 }
Пример #29
0
        internal Uri WriteBinaryToFile(string key, bool writeToCacheDirectory)
        {
            ProtectedBinary pb = Entry.Binaries.Get(key);

            System.Diagnostics.Debug.Assert(pb != null);
            if (pb == null)
            {
                throw new ArgumentException();
            }


            ISharedPreferences prefs           = PreferenceManager.GetDefaultSharedPreferences(this);
            string             binaryDirectory = prefs.GetString(GetString(Resource.String.BinaryDirectory_key), GetString(Resource.String.BinaryDirectory_default));

            if (writeToCacheDirectory)
            {
                binaryDirectory = CacheDir.Path + File.Separator + AttachmentContentProvider.AttachmentCacheSubDir;
            }

            string filepart = key;

            if (writeToCacheDirectory)
            {
                filepart = filepart.Replace(" ", "");
            }
            var targetFile = new File(binaryDirectory, filepart);

            File parent = targetFile.ParentFile;

            if (parent == null || (parent.Exists() && !parent.IsDirectory))
            {
                Toast.MakeText(this,
                               Resource.String.error_invalid_path,
                               ToastLength.Long).Show();
                return(null);
            }

            if (!parent.Exists())
            {
                // Create parent directory
                if (!parent.Mkdirs())
                {
                    Toast.MakeText(this,
                                   Resource.String.error_could_not_create_parent,
                                   ToastLength.Long).Show();
                    return(null);
                }
            }
            string filename = targetFile.AbsolutePath;
            Uri    fileUri  = Uri.FromFile(targetFile);

            byte[] pbData = pb.ReadData();
            try
            {
                System.IO.File.WriteAllBytes(filename, pbData);
            }
            catch (Exception exWrite)
            {
                Toast.MakeText(this, GetString(Resource.String.SaveAttachment_Failed, new Java.Lang.Object[] { filename })
                               + exWrite.Message, ToastLength.Long).Show();
                return(null);
            }
            finally
            {
                MemUtil.ZeroByteArray(pbData);
            }
            Toast.MakeText(this, GetString(Resource.String.SaveAttachment_doneMessage, new Java.Lang.Object[] { filename }), ToastLength.Short).Show();
            if (writeToCacheDirectory)
            {
                return(Uri.Parse("content://" + AttachmentContentProvider.Authority + "/"
                                 + filename));
            }
            return(fileUri);
        }
Пример #30
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            try {
                starting = true;

                //verifyStoragePermissions();

                Thread.CurrentThread.CurrentCulture =
                    System.Globalization.CultureInfo.InvariantCulture;

                //RequestWindowFeature(WindowFeatures.ActionBar);

                //Window.AddFlags(WindowManagerFlags.Fullscreen);
                //ActionBar.SetDisplayShowHomeEnabled(true);

                ActionBar.SetDisplayShowTitleEnabled(false);
                ActionBar.SetDisplayShowHomeEnabled(false);
                ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;

                /*var setHasEmbeddedTabsMethod = ActionBar.Class
                 *        .GetDeclaredMethod("setHasEmbeddedTabs", Java.Lang.Boolean.Type);
                 * setHasEmbeddedTabsMethod.Accessible=true;
                 * setHasEmbeddedTabsMethod.Invoke(ActionBar, true);*/

                //ActionBar.MenuVisibility = true;
                //ActionBar.DisplayOptions=ActionBarDisplayOptions
                SetContentView(Resource.Layout.Main);

                gridView1         = FindViewById <GridView>(Resource.Id.gridView1);
                ladapter          = new CustomAdapter(this, gridView1);
                gridView1.Adapter = ladapter;

                parser = new Parser(this, ladapter);

                statusText = FindViewById <TextView>(Resource.Id.StatusText);

                /*statusTimer = new System.Timers.Timer(10 * 1000);
                 * statusTimer.Elapsed += timer_Elapsed;
                 * statusTimer.AutoReset = false;*/

                statusText.Visibility = Android.Views.ViewStates.Invisible;
                statusText.Text       = "";

                // initalize menu
                menuIcon = FindViewById <ImageView>(Resource.Id.menuIcon);
                PopupMenu menu = new PopupMenu(this, menuIcon);
                menu.Inflate(Resource.Menu.OptionsMenu);
                //menu.Menu.FindItem(Resource.Id.selectionMode).SetCheckable(true);

                menuIcon.Click += (s, arg) => {
                    menu.Show();
                };
                menuIcon.Clickable  = true;
                menu.MenuItemClick += Menu_MenuItemClick;

                prefIcon = FindViewById <ImageView>(Resource.Id.prefIcon);
                PopupMenu prefMenu = new PopupMenu(this, prefIcon);
                prefMenu.Inflate(Resource.Menu.Wrench);
                //menu.Menu.FindItem(Resource.Id.selectionMode).SetCheckable(true);

                prefIcon.Click += (s, arg) => {
                    prefMenu.Show();
                };
                prefIcon.Clickable      = true;
                prefMenu.MenuItemClick += Menu_MenuItemClick;

                // context menu
                RegisterForContextMenu(gridView1);

                bluetoothHandler = new BluetoothHandler(this, parser);

                tabs = new List <Tab>();

                prefs = PreferenceManager.GetDefaultSharedPreferences(this);

                if (prefs.Contains("tabs"))
                {
                    // read saved stuff
                    LoadTabs();
                }
                else
                {
                    CreateDefaultTabs();
                }

                convertToImperial = prefs.GetBoolean("convertToImperial", false);
                prefMenu.Menu.FindItem(Resource.Id.metric)
                .SetChecked(!convertToImperial);

                gridView1.Clickable  = true;
                gridView1.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) => {
                    int packetId = ladapter[e.Position].packetId;
                    if (!ladapter[e.Position].selected)
                    {
                        sel = 1;
                    }
                    else
                    {
                        sel++;
                    }
                    if (sel > 3)
                    {
                        sel = 0;
                    }

                    if (sel == 0 || sel == 1)
                    {
                        ladapter[e.Position].selected = sel == 1;
                        ladapter.Touch(ladapter[e.Position]);
                    }
                    else
                    {
                        foreach (var item in ladapter.items.Where(x => x.packetId == packetId))
                        {
                            item.selected = sel == 2;
                            ladapter.Touch(item);
                        }
                    }
                    //ladapter.NotifyDataSetChanged();
                };


                var VersionName = PackageManager.GetPackageInfo(PackageName, 0).VersionName;
                //Toast.MakeText(this, "Version " + VersionName, ToastLength.Long).Show();
                prefMenu.Menu.Add("Version " + VersionName);
                var StoredVersion = prefs.GetString("version", "");
                if (StoredVersion != VersionName)
                {
                    AlertDialog.Builder alert = new AlertDialog.Builder(this);
                    alert.SetTitle("Welcome to Scan My Tesla version " + VersionName + "!");

                    if (StoredVersion == "" && prefs.All.Keys.Any()) // if there are any prefs in here, must mean we are upgrading
                    {
                        alert.SetMessage(                            // but version recording started in 1.3.0, so upgrading from earlier than that
                            "This version has some new and redesigned tabs.\n" +
                            "Use 'Factory reset all tabs' from the left menu if you want the new layout.\n" +
                            "Or, you can select 'New tab' from the right menu to add a single tab from the templates.");
                    }

                    alert.SetCancelable(true);
                    alert.SetPositiveButton("Changelog", (senderAlert, args) => {
                        var uri    = Android.Net.Uri.Parse("https://sites.google.com/view/scanmytesla/changelog");
                        var intent = new Intent(Intent.ActionView, uri);
                        StartActivity(intent);
                    });

                    alert.SetNegativeButton("Close", (senderAlert, args) => {
                    });

                    Dialog dialog = alert.Create();
                    dialog.Show();

                    PutPref("version", VersionName);
                }


#if !disablebluetooth
                var storedDevice = prefs.GetString("device", "");
                if (storedDevice == "")
                {
                    StartActivityForResult(typeof(DeviceListActivity), 1);
                }
                else
                {
                    Intent intent = new Intent(this, typeof(MainActivity));
                    intent.PutExtra("device_address", storedDevice);
                    OnActivityResult(1, Result.Ok, intent);
                }

                var t = tabs.Where(x => x.name == prefs.GetString("currentTab", "")).FirstOrDefault();
                if (t != null)
                {
                    ActionBar.SelectTab(t.ActionBarTab);
                }

                //Finish();
#else
                var t = tabs.Where(x => x.name == prefs.GetString("currentTab", "")).FirstOrDefault();
                if (t != null)
                {
                    ActionBar.SelectTab(t.ActionBarTab);
                }

                bluetoothHandler.Initialize(null);

                Window.SetFlags(WindowManagerFlags.KeepScreenOn, WindowManagerFlags.KeepScreenOn);

                //bluetoothHandler.Start();
#endif
                starting = false;

                verifyStoragePermissions();

                /*if (LogTimer == null)
                 * LogTimer = new Timer(LogTimerCallback, null, 2000, 200);*/

                //SupportFunctions.Version = context.PackageManager.GetPackageInfo(context.PackageName, 0).VersionName;
                //prefs.GetInt("")
            }
            catch (Exception e) {
                //set alert for executing the task
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.SetTitle("Error");
                alert.SetMessage(e.ToString());
                alert.SetCancelable(false);
                alert.SetPositiveButton("OK", (senderAlert, args) => {
                    System.Environment.Exit(1);
                });

                Dialog dialog = alert.Create();
                dialog.Show();
            }
        }