android.content.SharedPreferences Java Examples

The following examples show how to use android.content.SharedPreferences. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: ZhihuDaily   Author: Lovemma   File: SharedPreferencesUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void put(Context context, String key, Object object) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, object.toString());
        }
//        editor.apply();
        SharedPreferencesCompat.apply(editor);
    }
 
Example #2
Source Project: LaunchTime   Author: quaap   File: MsgBox.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void showNewsMessage(final Context context, SharedPreferences prefs) {


        final int newsnum = 83;
        final int news = prefs.getInt("seennews", 0);
        if (news < newsnum) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                    showNews(context);

                }
            }, 3000);
            prefs.edit().putInt("seennews", newsnum).apply();
        }

    }
 
Example #3
Source Project: SABS   Author: nvmkpk   File: ContentBlocker57.java    License: MIT License 6 votes vote down vote up
@Override
public boolean enableBlocker() {
    //contentBlocker56.setUrlBlockLimit(15_000);
    if (contentBlocker56.enableBlocker()) {
        SharedPreferences sharedPreferences = App.get().getApplicationContext().getSharedPreferences("dnsAddresses", Context.MODE_PRIVATE);
        if (sharedPreferences.contains("dns1") && sharedPreferences.contains("dns2")) {
            String dns1 = sharedPreferences.getString("dns1", null);
            String dns2 = sharedPreferences.getString("dns2", null);
            if (dns1 != null && dns2 != null
                    && Patterns.IP_ADDRESS.matcher(dns1).matches()
                    && Patterns.IP_ADDRESS.matcher(dns2).matches()) {
                this.setDns(dns1, dns2);
            }
            Log.d(TAG, "Previous dns addresses has been applied. " + dns1 + " " + dns2);
        }
        return true;
    }
    return false;
}
 
Example #4
Source Project: FairEmail   Author: M66B   File: AdapterAccount.java    License: GNU General Public License v3.0 6 votes vote down vote up
AdapterAccount(final Fragment parentFragment, boolean settings) {
    this.parentFragment = parentFragment;
    this.settings = settings;

    this.context = parentFragment.getContext();
    this.owner = parentFragment.getViewLifecycleOwner();
    this.inflater = LayoutInflater.from(context);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean highlight_unread = prefs.getBoolean("highlight_unread", true);
    this.colorUnread = Helper.resolveColor(context, highlight_unread ? R.attr.colorUnreadHighlight : android.R.attr.textColorPrimary);
    this.textColorSecondary = Helper.resolveColor(context, android.R.attr.textColorSecondary);

    this.DTF = Helper.getDateTimeInstance(context, DateFormat.SHORT, DateFormat.SHORT);

    setHasStableIds(true);

    owner.getLifecycle().addObserver(new LifecycleObserver() {
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        public void onDestroyed() {
            Log.d(AdapterAccount.this + " parent destroyed");
            AdapterAccount.this.parentFragment = null;
        }
    });
}
 
Example #5
Source Project: kcanotify_h5-master   Author: qly5213   File: MainActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
@SuppressLint("ApplySharedPref")
private void setDefaultPreferences() {
    SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();
    for (String prefKey : PREFS_LIST) {
        if (!pref.contains(prefKey)) {
            Log.e("KCA", prefKey + " pref add");
            String value = SettingActivity.getDefaultValue(prefKey);
            if (value.startsWith("R.string")) {
                editor.putString(prefKey, getString(getId(value.replace("R.string.", ""), R.string.class)));
            } else if (value.startsWith("boolean_")) {
                editor.putBoolean(prefKey, Boolean.parseBoolean(value.replace("boolean_", "")));
            } else {
                editor.putString(prefKey, value);
            }
        }
    }
    editor.commit();
}
 
Example #6
Source Project: mvvm-template   Author: duyp   File: PrefHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param key
 *         ( the Key to used to retrieve this data later  )
 * @param value
 *         ( any kind of primitive values  )
 *         <p/>
 *         non can be null!!!
 */
@SuppressLint("ApplySharedPref") public static <T> void set(@NonNull String key, @Nullable T value) {
    if (InputHelper.isEmpty(key)) {
        throw new NullPointerException("Key must not be null! (key = " + key + "), (value = " + value + ")");
    }
    SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(App.getInstance()).edit();
    if (InputHelper.isEmpty(value)) {
        clearKey(key);
        return;
    }
    if (value instanceof String) {
        edit.putString(key, (String) value);
    } else if (value instanceof Integer) {
        edit.putInt(key, (Integer) value);
    } else if (value instanceof Long) {
        edit.putLong(key, (Long) value);
    } else if (value instanceof Boolean) {
        edit.putBoolean(key, (Boolean) value);
    } else if (value instanceof Float) {
        edit.putFloat(key, (Float) value);
    } else {
        edit.putString(key, value.toString());
    }
    edit.commit();//apply on UI
}
 
Example #7
Source Project: AOSP-Kayboard-7.1.2   Author: sergchil   File: WordListPreference.java    License: Apache License 2.0 6 votes vote down vote up
private void enableDict() {
    final Context context = getContext();
    final SharedPreferences prefs = CommonPreferences.getCommonPreferences(context);
    CommonPreferences.enable(prefs, mWordlistId);
    // Explicit enabling by the user : allow downloading on metered data connection.
    UpdateHandler.markAsUsed(context, mClientId, mWordlistId, mVersion, mStatus, true);
    if (MetadataDbHelper.STATUS_AVAILABLE == mStatus) {
        setStatus(MetadataDbHelper.STATUS_DOWNLOADING);
    } else if (MetadataDbHelper.STATUS_DISABLED == mStatus
            || MetadataDbHelper.STATUS_DELETING == mStatus) {
        // If the status is DELETING, it means Android Keyboard
        // has not deleted the word list yet, so we can safely
        // turn it to 'installed'. The status DISABLED is still supported internally to
        // avoid breaking older installations and all but there should not be a way to
        // disable a word list through the interface any more.
        setStatus(MetadataDbHelper.STATUS_INSTALLED);
    } else {
        Log.e(TAG, "Unexpected state of the word list for enabling " + mStatus);
    }
}
 
Example #8
Source Project: iGap-Android   Author: RooyeKhat-Media   File: FragmentLanguageViewModel.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public void onClickEnglish(View v) {
    if (!G.selectedLanguage.equals("en")) {

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(SHP_SETTING.KEY_LANGUAGE, "English");
        editor.apply();
        G.selectedLanguage = "en";
        G.updateResources(G.currentActivity);
        HelperCalander.isPersianUnicode = false;
        HelperCalander.isLanguagePersian = false;
        HelperCalander.isLanguageArabic = false;
        G.isAppRtl = false;
        if (onRefreshActivity != null) {
            FragmentLanguage.languageChanged = true;
            G.isRestartActivity = true;
            onRefreshActivity.refresh("en");
        }
    }

    if (MusicPlayer.updateName != null) {
        MusicPlayer.updateName.rename();
    }

    fragmentLanguage.removeFromBaseFragment(fragmentLanguage);
}
 
Example #9
Source Project: FairEmail   Author: M66B   File: FragmentFolders.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get arguments
    Bundle args = getArguments();
    account = args.getLong("account", -1);
    primary = args.getBoolean("primary");

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
    cards = prefs.getBoolean("cards", true);
    compact = prefs.getBoolean("compact_folders", false);
    show_flagged = prefs.getBoolean("flagged_folders", false);

    setTitle(R.string.page_folders);
}
 
Example #10
Source Project: styT   Author: stytooldex   File: SPUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 移除某个key值已经对应的值
 *
 * @param context
 * @param key
 */
public static void remove(Context context, String key) {
    SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.remove(key);
    SharedPreferencesCompat.apply(editor);
}
 
Example #11
Source Project: input-samples   Author: android   File: ManualActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.multidataset_service_manual_activity);
    SharedPreferences sharedPreferences =
            getSharedPreferences(LocalAutofillDataSource.SHARED_PREF_KEY, Context.MODE_PRIVATE);
    DefaultFieldTypesSource defaultFieldTypesSource =
            DefaultFieldTypesLocalJsonSource.getInstance(getResources(),
                    new GsonBuilder().create());
    AutofillDao autofillDao = AutofillDatabase.getInstance(this,
            defaultFieldTypesSource, new AppExecutors()).autofillDao();
    mLocalAutofillDataSource = LocalAutofillDataSource.getInstance(sharedPreferences,
            autofillDao, new AppExecutors());
    mPackageName = getPackageName();
    mPreferences = MyPreferences.getInstance(this);
    mRecyclerView = findViewById(R.id.suggestionsList);
    mRecyclerView.addItemDecoration(new DividerItemDecoration(this, VERTICAL));
    mLocalAutofillDataSource.getAllAutofillDatasets(
            new DataCallback<List<DatasetWithFilledAutofillFields>>() {
                @Override
                public void onLoaded(List<DatasetWithFilledAutofillFields> datasets) {
                    mAllDatasets = datasets;
                    buildAdapter();
                }

                @Override
                public void onDataNotAvailable(String msg, Object... params) {

                }
            });
}
 
Example #12
Source Project: Camera2   Author: Yuloran   File: CameraPictureSizesCacher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return list of Sizes for provided cameraId.  Check first to see if we
 * have it in the cache for the current android.os.Build.
 * Note: This method calls Camera.open(), so the camera must be closed
 * before calling or null will be returned if sizes were not previously
 * cached.
 *
 * @param cameraId cameraID we would like sizes for.
 * @param context  valid android application context.
 * @return List of valid sizes, or null if the Camera can not be opened.
 */
public static List<Size> getSizesForCamera(int cameraId, Context context)
{
    Optional<List<Size>> cachedSizes = getCachedSizesForCamera(cameraId, context);
    if (cachedSizes.isPresent())
    {
        return cachedSizes.get();
    }

    // No cached value, so need to query Camera API.
    Camera thisCamera;
    try
    {
        thisCamera = Camera.open(cameraId);
    } catch (RuntimeException e)
    {
        // Camera open will fail if already open.
        return null;
    }
    if (thisCamera != null)
    {
        String key_build = PICTURE_SIZES_BUILD_KEY + cameraId;
        String key_sizes = PICTURE_SIZES_SIZES_KEY + cameraId;
        SharedPreferences defaultPrefs = PreferenceManager.getDefaultSharedPreferences(context);

        List<Size> sizes = Size.buildListFromCameraSizes(thisCamera.getParameters()
                .getSupportedPictureSizes());
        thisCamera.release();
        SharedPreferences.Editor editor = defaultPrefs.edit();
        editor.putString(key_build, Build.DISPLAY);
        editor.putString(key_sizes, Size.listToString(sizes));
        editor.apply();
        return sizes;
    }
    return null;
}
 
Example #13
Source Project: PKUCourses   Author: cbwang2016   File: AnnouncementListFragment.java    License: GNU General Public License v3.0 5 votes vote down vote up
private String getCachedAnnouncementsList() throws Exception {
    FragmentActivity fa = getActivity();
    if (fa == null) {
        throw new Exception("Unknown Error: Null getActivity()!");
    }
    SharedPreferences sharedPreferences = fa.getSharedPreferences("cached_xml", Context.MODE_PRIVATE);
    return sharedPreferences.getString("announcement_list_str", null);
}
 
Example #14
Source Project: apkextractor   Author: ghmxr   File: ExportRuleDialog.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void show(){
    super.show();
    getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(edit_apk.getText().toString().trim().equals("")||edit_zip.getText().toString().trim().equals("")){
                ToastManager.showToast(getContext(),getContext().getResources().getString(R.string.dialog_filename_toast_blank), Toast.LENGTH_SHORT);
                return;
            }

            final String apk_replaced_variables=EnvironmentUtil.getEmptyVariableString(edit_apk.getText().toString());
            final String zip_replaced_variables=EnvironmentUtil.getEmptyVariableString(edit_zip.getText().toString());
            if(!EnvironmentUtil.isALegalFileName(apk_replaced_variables)||!EnvironmentUtil.isALegalFileName(zip_replaced_variables)){
                ToastManager.showToast(getContext(),getContext().getResources().getString(R.string.file_invalid_name),Toast.LENGTH_SHORT);
                return;
            }

            SharedPreferences.Editor editor=settings.edit();
            editor.putString(Constants.PREFERENCE_FILENAME_FONT_APK, edit_apk.getText().toString());
            editor.putString(Constants.PREFERENCE_FILENAME_FONT_ZIP, edit_zip.getText().toString());
            int zip_selection=spinner.getSelectedItemPosition();
            switch(zip_selection){
                default:break;
                case 0:editor.putInt(Constants.PREFERENCE_ZIP_COMPRESS_LEVEL, Constants.PREFERENCE_ZIP_COMPRESS_LEVEL_DEFAULT);break;
                case 1:editor.putInt(Constants.PREFERENCE_ZIP_COMPRESS_LEVEL, Constants.ZIP_LEVEL_STORED);break;
                case 2:editor.putInt(Constants.PREFERENCE_ZIP_COMPRESS_LEVEL, Constants.ZIP_LEVEL_LOW);break;
                case 3:editor.putInt(Constants.PREFERENCE_ZIP_COMPRESS_LEVEL, Constants.ZIP_LEVEL_NORMAL);break;
                case 4:editor.putInt(Constants.PREFERENCE_ZIP_COMPRESS_LEVEL, Constants.ZIP_LEVEL_HIGH);break;
            }
            editor.apply();
            cancel();
        }
    });
}
 
Example #15
Source Project: Pocket-Plays-for-Twitch   Author: SebastianRask   File: Settings.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Stream Sleep Timer - Hour
 */

public void setStreamSleepTimerHour(int hour) {
	SharedPreferences.Editor editor = getEditor();
	editor.putInt(this.STREAM_SLEEP_HOUR, hour);
	editor.commit();
}
 
Example #16
Source Project: android-dev-challenge   Author: fjoglar   File: SettingsFragment.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    Preference preference = findPreference(key);
    if (null != preference) {
        if (!(preference instanceof CheckBoxPreference)) {
            setPreferenceSummary(preference, sharedPreferences.getString(key, ""));
        }
    }
}
 
Example #17
Source Project: tracker-control-android   Author: OxfordHCC   File: ServiceSinkhole.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void set(Intent intent) {
    // Get arguments
    int uid = intent.getIntExtra(EXTRA_UID, 0);
    String network = intent.getStringExtra(EXTRA_NETWORK);
    String pkg = intent.getStringExtra(EXTRA_PACKAGE);
    boolean blocked = intent.getBooleanExtra(EXTRA_BLOCKED, false);
    Log.i(TAG, "Set " + pkg + " " + network + "=" + blocked);

    // Get defaults
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ServiceSinkhole.this);
    boolean default_wifi = settings.getBoolean("whitelist_wifi", true);
    boolean default_other = settings.getBoolean("whitelist_other", true);

    // Update setting
    SharedPreferences prefs = getSharedPreferences(network, Context.MODE_PRIVATE);
    if (blocked == ("wifi".equals(network) ? default_wifi : default_other))
        prefs.edit().remove(pkg).apply();
    else
        prefs.edit().putBoolean(pkg, blocked).apply();

    // Apply rules
    ServiceSinkhole.reload("notification", ServiceSinkhole.this, false);

    // Update notification
    notifyNewApplication(uid);

    // Update UI
    Intent ruleset = new Intent(ActivityMain.ACTION_RULES_CHANGED);
    LocalBroadcastManager.getInstance(ServiceSinkhole.this).sendBroadcast(ruleset);
}
 
Example #18
Source Project: firefox-echo-show   Author: mozilla-mobile   File: UrlMatcher.java    License: Mozilla Public License 2.0 5 votes vote down vote up
private void loadPrefs(final Context context) {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    for (final Map.Entry<String, String> entry : categoryPrefMap.entrySet()) {
        final boolean prefValue = prefs.getBoolean(entry.getKey(), true);
        setCategoryEnabled(entry.getValue(), prefValue);
    }
}
 
Example #19
Source Project: TelePlus-Android   Author: TelePlusDev   File: Emoji.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void saveRecentEmoji() {
    SharedPreferences preferences = MessagesController.getGlobalEmojiSettings();
    StringBuilder stringBuilder = new StringBuilder();
    for (HashMap.Entry<String, Integer> entry : emojiUseHistory.entrySet()) {
        if (stringBuilder.length() != 0) {
            stringBuilder.append(",");
        }
        stringBuilder.append(entry.getKey());
        stringBuilder.append("=");
        stringBuilder.append(entry.getValue());
    }
    preferences.edit().putString("emojis2", stringBuilder.toString()).commit();
}
 
Example #20
Source Project: Paddle-Lite-Demo   Author: PaddlePaddle   File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
public void initSettings() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();
    editor.commit();
    SettingsActivity.resetSettings();
}
 
Example #21
Source Project: XERUNG   Author: mityung   File: ProfileSetting.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void dserializeCity() {
    SharedPreferences prefs = context.getSharedPreferences(Vars.SHARED_PREFS_FILE, Context.MODE_PRIVATE);
    LinkedHashMap<String, String> currentTasks = null;
    try {
        currentTasks = (LinkedHashMap<String, String>) new ObjectSerializer().deserialize(prefs.getString("fetchCity", new ObjectSerializer().serialize(new LinkedHashMap<String, String>())));
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (currentTasks != null) {
        cityNameId = currentTasks;
    }

}
 
Example #22
Source Project: MvpRxJavaRetrofitOkhttp   Author: jopenbox   File: SPUtils.java    License: MIT License 5 votes vote down vote up
/**
 * 反射查找apply的方法
 *
 * @return
 */
@SuppressWarnings({"unchecked", "rawtypes"})
private static Method findApplyMethod() {
    try {
        Class clz = SharedPreferences.Editor.class;
        return clz.getMethod("apply");
    } catch (NoSuchMethodException e) {
    }
    return null;
}
 
Example #23
Source Project: green_android   Author: Blockstream   File: ListTransactionsAdapter.java    License: GNU General Public License v3.0 5 votes vote down vote up
public ListTransactionsAdapter(final Activity activity,
                               final NetworkData networkData,
                               final List<TransactionData> txItems,
                               final SPV spv, final OnTxSelected selector) {
    mTxItems = txItems;
    mActivity = activity;
    mNetworkData = networkData;
    final SharedPreferences preferences = activity.getSharedPreferences(mNetworkData.getNetwork(), MODE_PRIVATE);
    isSpvEnabled = preferences.getBoolean(PrefKeys.SPV_ENABLED, false);
    mSPV = spv;
    mOnTxSelected = selector;
}
 
Example #24
Source Project: o2oa   Author: o2oa   File: OfflineRecogParams.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public Map<String, Object> fetch(SharedPreferences sp) {

        Map<String, Object> map = super.fetch(sp);
        map.put(SpeechConstant.DECODER, 2);
        map.remove(SpeechConstant.PID); // 去除pid,只支持中文
        return map;

    }
 
Example #25
Source Project: pushfish-android   Author: PushFish   File: SettingsActivity.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static String getRegisterUrl(Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    boolean useCustom = preferences.getBoolean("server_use_custom", false);

    if (useCustom) {
        String url = preferences.getString("server_custom_url", DEFAULT_PUSHFISH_GCM_REGISTER_URL);
        return url.replaceAll("/+$", "");
    } else {
        return DEFAULT_PUSHFISH_GCM_REGISTER_URL;
    }
}
 
Example #26
Source Project: abnd-track-pomodoro-timer-app   Author: google-udacity-india-scholars   File: SettingsActivity.java    License: MIT License 5 votes vote down vote up
/**
 * Save the latest selected item position from the spinners
 * into SharedPreferences
 *
 * @param parent
 * @param view
 * @param position
 * @param id
 */
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // initialize the editor
    SharedPreferences.Editor editor = preferences.edit();
    // switch case to handle different spinners
    switch (parent.getId()) {
        // item selected in work duration spinner
        case R.id.work_duration_spinner:
            // save the corresponding item position
            editor.putInt(getString(R.string.work_duration_key), position);
            break;
        // item selected in short break duration spinner
        case R.id.short_break_duration_spinner:
            // save the corresponding item position
            editor.putInt(getString(R.string.short_break_duration_key), position);
            break;
        // item selected in long break duration spinner
        case R.id.long_break_duration_spinner:
            // save the corresponding item position
            editor.putInt(getString(R.string.long_break_duration_key), position);
        case R.id.start_long_break_after_spinner:
            // save the corresponding item position
            editor.putInt(getString(R.string.start_long_break_after_key), position);

    }
    editor.apply();
}
 
Example #27
Source Project: simple-keyboard   Author: rkkr   File: AdvancedSettingsFragment.java    License: Apache License 2.0 5 votes vote down vote up
private void refreshEnablingsOfSettings() {
    final SharedPreferences prefs = getSharedPreferences();
    final Resources res = getResources();
    setPreferenceEnabled(Settings.PREF_VIBRATION_DURATION_SETTINGS,
            Settings.readVibrationEnabled(prefs, res));
    setPreferenceEnabled(Settings.PREF_KEYPRESS_SOUND_VOLUME,
            Settings.readKeypressSoundEnabled(prefs, res));
    final KeyboardTheme theme = KeyboardTheme.getKeyboardTheme(prefs);
    setPreferenceEnabled(Settings.PREF_KEYBOARD_COLOR,
            theme.mThemeId != KeyboardTheme.THEME_ID_SYSTEM
                    && theme.mThemeId != KeyboardTheme.THEME_ID_SYSTEM_BORDER);
}
 
Example #28
Source Project: iGap-Android   Author: RooyeKhat-Media   File: ActivityEnterPassCode.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    ActivityEnterPassCodeBinding activityEnterPassCodeBinding = DataBindingUtil.setContentView(this, R.layout.activity_enter_pass_code);
    activityManageSpaceViewModel = new ActivityEnterPassCodeViewModel(this, activityEnterPassCodeBinding);

    activityEnterPassCodeBinding.setActivityEnterPassCodeViewModel(activityManageSpaceViewModel);
    SharedPreferences sharedPreferences = G.currentActivity.getSharedPreferences(SHP_SETTING.FILE_NAME, MODE_PRIVATE);
    boolean isLinePattern = sharedPreferences.getBoolean(SHP_SETTING.KEY_PATTERN_TACTILE_DRAWN, true);

    activityEnterPassCodeBinding.patternLockView.setViewMode(PatternLockView.PatternViewMode.CORRECT);       // Set the current viee more
    activityEnterPassCodeBinding.patternLockView.setInStealthMode(!isLinePattern);                                     // Set the pattern in stealth mode (pattern drawing is hidden)
    activityEnterPassCodeBinding.patternLockView.setTactileFeedbackEnabled(true);                            // Enables vibration feedback when the pattern is drawn
    activityEnterPassCodeBinding.patternLockView.setInputEnabled(true);                                     // Disables any input from the pattern lock view completely

    activityEnterPassCodeBinding.patternLockView.setDotCount(4);
    activityEnterPassCodeBinding.patternLockView.setDotNormalSize((int) ResourceUtils.getDimensionInPx(G.currentActivity, R.dimen.dp22));
    activityEnterPassCodeBinding.patternLockView.setDotSelectedSize((int) ResourceUtils.getDimensionInPx(G.currentActivity, R.dimen.dp32));
    activityEnterPassCodeBinding.patternLockView.setPathWidth((int) ResourceUtils.getDimensionInPx(G.currentActivity, R.dimen.pattern_lock_path_width));
    activityEnterPassCodeBinding.patternLockView.setAspectRatioEnabled(true);
    activityEnterPassCodeBinding.patternLockView.setAspectRatio(PatternLockView.AspectRatio.ASPECT_RATIO_HEIGHT_BIAS);
    activityEnterPassCodeBinding.patternLockView.setNormalStateColor(ResourceUtils.getColor(G.currentActivity, R.color.white));
    activityEnterPassCodeBinding.patternLockView.setCorrectStateColor(ResourceUtils.getColor(G.currentActivity, R.color.white));
    activityEnterPassCodeBinding.patternLockView.setWrongStateColor(ResourceUtils.getColor(G.currentActivity, R.color.red));
    activityEnterPassCodeBinding.patternLockView.setDotAnimationDuration(150);
    activityEnterPassCodeBinding.patternLockView.setPathEndAnimationDuration(100);

}
 
Example #29
Source Project: blade-player   Author: Valou3433   File: SettingsActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public final void onActivityResult(final int requestCode, final int resultCode, final Intent resultData)
{
    if (resultCode == AppCompatActivity.RESULT_OK && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
    {
        //if (requestCode == REQUEST_CODE_STORAGE_ACCESS)
        //{
            // Get Uri from Storage Access Framework.
            Uri treeUri = resultData.getData();

            if(!treeUri.toString().endsWith("%3A"))
            {
                //show the user that we are not happy
                Toast.makeText(this, R.string.please_sd_root, Toast.LENGTH_LONG).show();
                return;
            }

            // Persist URI in shared preference so that you can use it later.
            SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCES_GENERAL_FILE_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("sdcard_uri", treeUri.toString());
            editor.apply();

            LibraryService.TREE_URI = treeUri;

            // Persist access permissions, so you dont have to ask again
            final int takeFlags = resultData.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            grantUriPermission(getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            Toast.makeText(this, getString(R.string.perm_granted) + " : " + treeUri, Toast.LENGTH_LONG).show();
        //}
    }
}
 
Example #30
Source Project: OAuth-2.0-Cookbook   Author: PacktPublishing   File: TokenStore.java    License: MIT License 5 votes vote down vote up
public void save(AccessToken accessToken) {
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean("authorized", true);
    editor.putString("access_token", accessToken.getValue());
    editor.putString("scope", accessToken.getScope());
    editor.putString("token_type", accessToken.getTokenType());
    editor.putLong("expires_in", accessToken.getExpiresIn());
    editor.putLong("issued_at", accessToken.getIssuedAt());
    editor.commit();
}