Example usage for android.preference CheckBoxPreference setOnPreferenceChangeListener

List of usage examples for android.preference CheckBoxPreference setOnPreferenceChangeListener

Introduction

In this page you can find the example usage for android.preference CheckBoxPreference setOnPreferenceChangeListener.

Prototype

public void setOnPreferenceChangeListener(OnPreferenceChangeListener onPreferenceChangeListener) 

Source Link

Document

Sets the callback to be invoked when this Preference is changed by the user (but before the internal state has been updated).

Usage

From source file:net.freifunk.android.discover.SettingsActivity.java

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    addPreferencesFromResource(R.xml.pref_data_sync);

    // get data via the key
    ArrayList<NodeMap> nodeMapArrayList = new ArrayList<NodeMap>(MapMaster.getInstance().getMaps().values());
    PreferenceCategory communities = (PreferenceCategory) findPreference("communities");

    // sort by Name
    Collections.sort(nodeMapArrayList, new NodeMapComparator());

    if (nodeMapArrayList != null && communities != null) {
        for (final NodeMap nm : nodeMapArrayList) {

            PreferenceScreen communityPreferenceScreen = getPreferenceManager()
                    .createPreferenceScreen(SettingsActivity.this);

            communityPreferenceScreen.setTitle(nm.getMapName());
            communityPreferenceScreen.setKey(nm.getMapName());

            final CheckBoxPreference deactivateCommunityPreference = new CheckBoxPreference(
                    SettingsActivity.this);

            // TODO: move Strings to resources
            deactivateCommunityPreference.setTitle("Community aktiv");
            deactivateCommunityPreference
                    .setSummary("deaktivieren, falls Community nicht auf der Karte angezeigt werden soll");
            deactivateCommunityPreference.setKey("community_deactivate_" + nm.getMapName());
            deactivateCommunityPreference.setChecked(nm.isActive());
            deactivateCommunityPreference
                    .setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

                        @Override
                        public boolean onPreferenceChange(Preference preference, Object newValue) {

                            Database db = Database.getInstance(null);

                            boolean newActive = newValue.toString().equals("true") ? true : false;

                            nm.setActive(newActive);
                            db.addNodeMap(nm);

                            // reload if set to active
                            if (newActive) {
                                nm.loadNodes();
                            } else {
                                nm.updateNodes();
                            }/* w ww  . j a v a 2s.  c  o m*/

                            return true;
                        }
                    });

            EditTextPreference editCommunityPreference = new EditTextPreference(SettingsActivity.this);

            // TODO: move Strings to resources
            editCommunityPreference.setTitle("URL bearbeiten");
            editCommunityPreference.setSummary("aendern, falls eine andere Quelle genutzt werden soll.");
            editCommunityPreference.setKey("community_edit_" + nm.getMapName());
            editCommunityPreference.setText(nm.getMapUrl());

            editCommunityPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {

                    Database db = Database.getInstance(null);

                    // remove old nodes from map
                    nm.setActive(false);
                    EventBus.getInstance().post(new NodeResult(NodeResult.NodeResultType.UPDATE_NODES, nm));

                    // we should probably do this async as well
                    db.deleteAllNodesForMap(nm);

                    // load new nodes
                    NodeMap newMap = new NodeMap(nm.getMapName(), (String) newValue, true);
                    db.addNodeMap(newMap);

                    //HashMap<String, NodeMap> nodeResult = new HashMap<String, NodeMap>(1);
                    //nodeResult.put(nm.getMapName(), nm);

                    newMap.updateNodes();
                    //EventBus.getInstance().post(new NodeResult(NodeResult.NodeResultType.LOAD_NODES, nm));
                    //EventBus.getInstance().post(new NodeResult(NodeResult.NodeResultType.UPDATE_MAP, nodeResult));

                    return true;
                }
            });

            communityPreferenceScreen.addPreference(deactivateCommunityPreference);
            communityPreferenceScreen.addPreference(editCommunityPreference);

            communities.addPreference(communityPreferenceScreen);
        }
    }

    setupActionBar();

}

From source file:de.j4velin.wifiAutoOff.Preferences.java

@SuppressWarnings("deprecation")
@Override/*from w w w. j  a v a2s .  c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    if (BuildConfig.DEBUG && PermissionChecker.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED) {
        requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
    }

    status = (StatusPreference) findPreference("status");
    status.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(final Preference preference) {
            WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            boolean connected = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
            if (wm.isWifiEnabled() && !connected) {
                try {
                    startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK)
                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    Toast.makeText(Preferences.this, R.string.settings_not_found_, Toast.LENGTH_SHORT).show();
                }
            } else if (!wm.isWifiEnabled()) {
                wm.setWifiEnabled(true);
            } else {
                try {
                    startActivity(
                            new Intent(Settings.ACTION_WIFI_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    Toast.makeText(Preferences.this, R.string.settings_not_found_, Toast.LENGTH_SHORT).show();
                }
            }
            return true;
        }
    });

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    final CheckBoxPreference screen_off = (CheckBoxPreference) findPreference("off_screen_off");
    screen_off.setSummary(
            getString(R.string.for_at_least, prefs.getInt("screen_off_timeout", Receiver.TIMEOUT_SCREEN_OFF)));

    if (!keepWiFiOn(this)) {
        screen_off.setChecked(false);
    }

    screen_off.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                if (!keepWiFiOn(Preferences.this)) {
                    new AlertDialog.Builder(Preferences.this).setMessage(R.string.sleep_policy)
                            .setPositiveButton(R.string.adv_wifi_settings, new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    try {
                                        startActivity(new Intent(Settings.ACTION_WIFI_IP_SETTINGS)
                                                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                    } catch (Exception e) {
                                        Toast.makeText(Preferences.this, R.string.settings_not_found_,
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }).setNegativeButton(android.R.string.cancel, new OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                    return false;
                }
                if (android.os.Build.VERSION.SDK_INT >= 11) {
                    APILevel11Wrapper.showNumberPicker(Preferences.this, prefs, screen_off,
                            R.string.for_at_least, 1, 60, getString(R.string.minutes_before_turning_off_wifi_),
                            "screen_off_timeout", Receiver.TIMEOUT_SCREEN_OFF, false);
                } else {
                    showPre11NumberPicker(Preferences.this, prefs, screen_off, R.string.for_at_least, 1, 60,
                            getString(R.string.minutes_before_turning_off_wifi_), "screen_off_timeout",
                            Receiver.TIMEOUT_SCREEN_OFF, false);
                }
            }
            return true;
        }
    });

    findPreference("off_no_network").setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                if (android.os.Build.VERSION.SDK_INT >= 11) {
                    APILevel11Wrapper.showNumberPicker(Preferences.this, prefs, preference,
                            R.string.for_at_least, 1, 60, getString(R.string.minutes_before_turning_off_wifi_),
                            "no_network_timeout", Receiver.TIMEOUT_NO_NETWORK, false);
                } else {
                    showPre11NumberPicker(Preferences.this, prefs, preference, R.string.for_at_least, 1, 60,
                            getString(R.string.minutes_before_turning_off_wifi_), "no_network_timeout",
                            Receiver.TIMEOUT_NO_NETWORK, false);
                }
            }
            return true;
        }
    });

    final CheckBoxPreference on_at = (CheckBoxPreference) findPreference("on_at");
    on_at.setTitle(getString(R.string.at_summary, prefs.getString("on_at_time", Receiver.ON_AT_TIME)));
    on_at.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                String[] time = prefs.getString("on_at_time", Receiver.ON_AT_TIME).split(":");
                final TimePickerDialog dialog = new TimePickerDialog(Preferences.this, new OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        prefs.edit().putString("on_at_time",
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)).commit();
                        on_at.setTitle(getString(R.string.at_summary,
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)));
                    }
                }, Integer.parseInt(time[0]), Integer.parseInt(time[1]), true);
                dialog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        on_at.setChecked(false);
                    }
                });
                dialog.setTitle(getString(R.string.turn_wifi_on_at_));
                dialog.show();
            }
            return true;
        }
    });

    final CheckBoxPreference off_at = (CheckBoxPreference) findPreference("off_at");
    off_at.setTitle(getString(R.string.at_summary, prefs.getString("off_at_time", Receiver.OFF_AT_TIME)));
    off_at.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                String[] time = prefs.getString("off_at_time", Receiver.OFF_AT_TIME).split(":");
                final TimePickerDialog dialog = new TimePickerDialog(Preferences.this, new OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        prefs.edit().putString("off_at_time",
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)).commit();
                        off_at.setTitle(getString(R.string.at_summary,
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)));
                    }
                }, Integer.parseInt(time[0]), Integer.parseInt(time[1]), true);
                dialog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        off_at.setChecked(false);
                    }
                });
                dialog.setTitle(getString(R.string.turn_wifi_off_at_));
                dialog.show();
            }
            return true;
        }
    });

    final Preference on_every = findPreference("on_every");
    final String[] time_names = getResources().getStringArray(R.array.time_names);
    // default 2 hours
    on_every.setTitle(getString(R.string.every_summary, prefs.getString("on_every_str", time_names[4])));
    on_every.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                AlertDialog.Builder builder = new AlertDialog.Builder(Preferences.this);
                builder.setTitle(R.string.turn_wifi_on_every).setItems(time_names,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                prefs.edit().putInt("on_every_time_min", time_values[which])
                                        .putString("on_every_str", time_names[which]).commit();
                                on_every.setTitle(getString(R.string.every_summary, time_names[which]));
                            }
                        });
                builder.create().show();
            }
            return true;
        }
    });

    Preference locations = findPreference("locations");
    if (BuildConfig.FLAVOR.equals("play")) {
        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_NETWORK)) {
            locations.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(final Preference preference) {
                    startActivity(new Intent(Preferences.this, Locations.class));
                    return true;
                }
            });
        } else {
            locations.setEnabled(false);
        }
    } else {
        locations.setSummary("Not available in F-Droid version");
        locations.setEnabled(false);
    }

    final Preference power = findPreference("power_connected");
    power.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((boolean) newValue) {
                Intent battery = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
                if (battery != null && battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) > 0) {
                    // already connected to external power
                    prefs.edit().putBoolean("ignore_screen_off", true).commit();
                }
            } else {
                prefs.edit().putBoolean("ignore_screen_off", false).commit();
            }
            return true;
        }
    });
}

From source file:com.almalence.opencam.Fragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    thiz = this;/*from w w w  . j  a  va2  s  .  c om*/

    String settings = getArguments().getString("type");

    ApplicationScreen.getPluginManager().loadHeaderContent(settings, this);

    if (null == getPreferenceScreen())
        return;
    for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
        initSummary(getPreferenceScreen().getPreference(i));
    }

    Preference nightPreference = findPreference("night");
    if (nightPreference != null) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        if (prefs.getBoolean("useCamera2Pref", false)) {
            getPreferenceScreen().removePreference(nightPreference);
        } else {
            Preference superPreference = findPreference("super");
            getPreferenceScreen().removePreference(superPreference);
        }
    }

    final SeekBarPreference brightnessPref = (SeekBarPreference) this.findPreference("brightnessPref");
    if (brightnessPref != null) {
        // Set seekbar summary :
        float gamma = PreferenceManager.getDefaultSharedPreferences(getActivity()).getFloat("gammaPref", 0.5f);
        brightnessPref.setSummary(
                this.getString(R.string.Pref_Super_BrightnessEnhancementValue).replace("$1", "" + gamma));
        brightnessPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            private final Map<Integer, Float> gamma_map = new HashMap<Integer, Float>() {
                {
                    put(0, 0.5f);
                    put(1, 0.55f);
                    put(2, 0.6f);
                    put(3, 0.65f);
                    put(4, 0.7f);
                }
            };

            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                int radius = (Integer) newValue;
                float gamma = gamma_map.get(radius);
                PreferenceManager
                        .getDefaultSharedPreferences(Fragment.thiz.getActivity().getApplicationContext()).edit()
                        .putFloat("gammaPref", gamma).commit();
                brightnessPref.setSummary(getActivity()
                        .getString(R.string.Pref_Super_BrightnessEnhancementValue).replace("$1", "" + gamma));
                return true;
            }
        });
    }

    final CheckBoxPreference upscalePref = (CheckBoxPreference) this.findPreference("upscaleResult");
    if (upscalePref != null) {
        Size size = CameraController.getMaxCameraImageSize(CameraController.YUV);
        long resMpx = 0;
        float mpix = 0.0f;
        if (size != null) {
            resMpx = (long) ((long) size.getWidth() * (long) size.getHeight() * 2.25);
            mpix = (float) resMpx / 1000000.f;
        }

        String name = String.format("%3.1f Mpix ", mpix);

        upscalePref.setSummary(
                getActivity().getString(R.string.Pref_Super_SummaryUpscale).replace("$1", "" + name));
    }

    Preference cameraParameters = findPreference("camera_parameters");
    if (cameraParameters != null) {
        cameraParameters.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                try {
                    showCameraParameters();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return true;
            }
        });
    }

    CheckBoxPreference helpPref = (CheckBoxPreference) findPreference("showHelpPrefCommon");
    if (helpPref != null)
        helpPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                if (((CheckBoxPreference) preference).isChecked()) {
                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(MainScreen.getMainContext());
                    Editor prefsEditor = prefs.edit();
                    prefsEditor.putBoolean("droShowHelp", true);
                    prefsEditor.putBoolean("sequenceRemovalShowHelp", true);
                    prefsEditor.putBoolean("panoramaShowHelp", true);
                    prefsEditor.putBoolean("superShowHelp", true);
                    prefsEditor.putBoolean("groupshotRemovalShowHelp", true);
                    prefsEditor.putBoolean("objectRemovalShowHelp", true);
                    prefsEditor.putBoolean("bestShotShowHelp", true);
                    prefsEditor.commit();
                }

                return true;
            }
        });

    EditTextPreference prefix = (EditTextPreference) this
            .findPreference(getResources().getString(R.string.Preference_SavePathPrefixValue));
    EditTextPreference postfix = (EditTextPreference) this
            .findPreference(getResources().getString(R.string.Preference_SavePathPostfixValue));
    initExportName(null, null);

    if (prefix != null) {
        prefix.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                initExportName(preference, newValue);
                return true;
            }
        });
    }

    if (postfix != null) {
        postfix.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                initExportName(preference, newValue);
                return true;
            }
        });
    }

    Preference sonyPreference = findPreference(MainScreen.sSonyCamerasPref);
    if (sonyPreference != null) {
        sonyPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                boolean sonyCamerasAvailable = (Boolean) newValue;
                if (sonyCamerasAvailable) {
                    Toast.makeText(getActivity(),
                            getActivity().getString(R.string.pref_general_more_sonyCamera_available),
                            Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });
    }

    ListPreference saveToPreference = (ListPreference) this
            .findPreference(getResources().getString(R.string.Preference_SaveToValue));

    // if android 5+, then remove "save to SD card" option. Because it's
    // equals to "save to custom folder" option.
    if (saveToPreference != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CharSequence[] entries = saveToPreference.getEntries();
        CharSequence[] entriyValues = saveToPreference.getEntryValues();

        CharSequence[] newEntries = new String[2];
        CharSequence[] newEntriyValues = new String[2];

        newEntries[0] = entries[0];
        newEntries[1] = entries[2];
        newEntriyValues[0] = entriyValues[0];
        newEntriyValues[1] = entriyValues[2];

        saveToPreference.setEntries(newEntries);
        saveToPreference.setEntryValues(newEntriyValues);
    }
    if (saveToPreference != null) {

        saveToPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                int v = -1;

                int v_old = 0;

                try {
                    v = Integer.parseInt(newValue.toString());
                    v_old = Integer.parseInt(((ListPreference) preference).getValue());
                } catch (NumberFormatException e) {

                }

                if ((v == 2 || v == 1) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                        Toast.makeText(MainScreen.getInstance(),
                                MainScreen.getAppResources()
                                        .getString(R.string.pref_advanced_saving_saveToPref_CantSaveToSD),
                                Toast.LENGTH_LONG).show();

                        if (isDeviceRooted()) {
                            Intent intent = new Intent(Preferences.thiz, FolderPicker.class);

                            intent.putExtra(MainScreen.sSavePathPref, v_old);

                            Preferences.thiz.startActivity(intent);

                            return true;
                        } else
                            return false;
                    }
                }

                if (v == 2 || v == 1) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                        startActivityForResult(intent, CHOOSE_FOLDER_CODE);
                    } else if (v != 1) {
                        Intent intent = new Intent(Preferences.thiz, FolderPicker.class);

                        intent.putExtra(MainScreen.sSavePathPref, v_old);

                        Preferences.thiz.startActivity(intent);
                    }
                }

                return true;
            }
        });
    }

    PreferenceCategory cat = (PreferenceCategory) this.findPreference("Pref_VFCommon_Preference_Category");
    if (cat != null) {
        CheckBoxPreference cp = (CheckBoxPreference) cat.findPreference("maxScreenBrightnessPref");
        if (cp != null) {
            cp.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    boolean value = Boolean.parseBoolean(newValue.toString());
                    setScreenBrightness(value);
                    return true;
                }
            });
        }
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
    boolean MaxScreenBrightnessPreference = prefs.getBoolean("maxScreenBrightnessPref", false);
    setScreenBrightness(MaxScreenBrightnessPreference);
}

From source file:com.nttec.everychan.chans.makaba.MakabaModule.java

/**   ?  ( .. https) */
private void addDomainPreferences(PreferenceGroup group) {
    Context context = group.getContext();
    Preference.OnPreferenceChangeListener updateDomainListener = new Preference.OnPreferenceChangeListener() {
        @Override/*  w w w . jav  a  2s  .c  o  m*/
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (preference.getKey().equals(getSharedKey(PREF_KEY_DOMAIN))) {
                updateDomain((String) newValue,
                        preferences.getBoolean(getSharedKey(PREF_KEY_USE_HTTPS_MAKABA), true));
                return true;
            } else if (preference.getKey().equals(getSharedKey(PREF_KEY_USE_HTTPS_MAKABA))) {
                updateDomain(preferences.getString(getSharedKey(PREF_KEY_DOMAIN), DEFAULT_DOMAIN),
                        (boolean) newValue);
                return true;
            }
            return false;
        }
    };
    PreferenceCategory domainCat = new PreferenceCategory(context);
    domainCat.setTitle(R.string.makaba_prefs_domain_category);
    group.addPreference(domainCat);
    EditTextPreference domainPref = new EditTextPreference(context); //  
    domainPref.setTitle(R.string.pref_domain);
    domainPref.setDialogTitle(R.string.pref_domain);
    domainPref.setSummary(resources.getString(R.string.pref_domain_summary, DOMAINS_HINT));
    domainPref.setKey(getSharedKey(PREF_KEY_DOMAIN));
    domainPref.getEditText().setHint(DEFAULT_DOMAIN);
    domainPref.getEditText().setSingleLine();
    domainPref.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
    domainPref.setOnPreferenceChangeListener(updateDomainListener);
    domainCat.addPreference(domainPref);
    CheckBoxPreference httpsPref = new LazyPreferences.CheckBoxPreference(context); //? "? https"
    httpsPref.setTitle(R.string.pref_use_https);
    httpsPref.setSummary(R.string.pref_use_https_summary);
    httpsPref.setKey(getSharedKey(PREF_KEY_USE_HTTPS_MAKABA));
    httpsPref.setDefaultValue(true);
    httpsPref.setOnPreferenceChangeListener(updateDomainListener);
    domainCat.addPreference(httpsPref);
}

From source file:org.linphone.SettingsFragment.java

private void initAudioSettings() {
    PreferenceCategory codecs = (PreferenceCategory) findPreference(getString(R.string.pref_codecs_key));
    if (codecs == null)
        return;/*from   www .j  a v a  2  s.  c o m*/

    codecs.removeAll();

    LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
    for (final PayloadType pt : lc.getAudioCodecs()) {
        CheckBoxPreference codec = new CheckBoxPreference(LinphoneService.instance());
        codec.setTitle(pt.getMime());
        codec.setSummary(pt.getRate() + " Hz");
        codec.setChecked(lc.isPayloadTypeEnabled(pt));

        codec.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                boolean enable = (Boolean) newValue;
                try {
                    LinphoneManager.getLcIfManagerNotDestroyedOrNull().enablePayloadType(pt, enable);
                } catch (LinphoneCoreException e) {
                    e.printStackTrace();
                }
                return true;
            }
        });

        codecs.addPreference(codec);
    }

    CheckBoxPreference echoCancellation = (CheckBoxPreference) findPreference(
            getString(R.string.pref_echo_cancellation_key));
    echoCancellation.setChecked(mPrefs.isEchoCancellationEnabled());

    if (mPrefs.isEchoCancellationEnabled()) {
        Preference echoCalibration = findPreference(getString(R.string.pref_echo_canceller_calibration_key));
        echoCalibration
                .setSummary(String.format(getString(R.string.ec_calibrated), mPrefs.getEchoCalibration()));
    }

    CheckBoxPreference adaptiveRateControl = (CheckBoxPreference) findPreference(
            getString(R.string.pref_adaptive_rate_control_key));
    adaptiveRateControl.setChecked(mPrefs.isAdaptiveRateControlEnabled());

    ListPreference adaptiveRateAlgorithm = (ListPreference) findPreference(
            getString(R.string.pref_adaptive_rate_algorithm_key));
    adaptiveRateAlgorithm.setSummary(String.valueOf(mPrefs.getAdaptiveRateAlgorithm()));
    adaptiveRateAlgorithm.setValue(String.valueOf(mPrefs.getAdaptiveRateAlgorithm()));

    ListPreference bitrateLimit = (ListPreference) findPreference(
            getString(R.string.pref_codec_bitrate_limit_key));
    bitrateLimit.setSummary(String.valueOf(mPrefs.getCodecBitrateLimit()));
    bitrateLimit.setValue(String.valueOf(mPrefs.getCodecBitrateLimit()));
}

From source file:org.linphone.SettingsFragment.java

private void initVideoSettings() {
    initializePreferredVideoSizePreferences(
            (ListPreference) findPreference(getString(R.string.pref_preferred_video_size_key)));

    PreferenceCategory codecs = (PreferenceCategory) findPreference(getString(R.string.pref_video_codecs_key));

    if (codecs == null)
        return;/*w ww .ja  va  2  s . c o  m*/

    codecs.removeAll();

    LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
    for (final PayloadType pt : lc.getVideoCodecs()) {
        CheckBoxPreference codec = new CheckBoxPreference(LinphoneService.instance());
        codec.setTitle(pt.getMime());

        if (!pt.getMime().equals("VP8")) {
            if (getResources().getBoolean(R.bool.disable_all_patented_codecs_for_markets)) {
                continue;
            } else {
                if (!Version.hasFastCpuWithAsmOptim() && pt.getMime().equals("H264")) {
                    // Android without neon doesn't support H264
                    Log.w("CPU does not have asm optimisations available, disabling H264");
                    continue;
                }
            }
        }
        codec.setChecked(lc.isPayloadTypeEnabled(pt));

        codec.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                boolean enable = (Boolean) newValue;
                try {
                    LinphoneManager.getLcIfManagerNotDestroyedOrNull().enablePayloadType(pt, enable);
                } catch (LinphoneCoreException e) {
                    e.printStackTrace();
                }
                return true;
            }
        });

        codecs.addPreference(codec);
    }

    ((CheckBoxPreference) findPreference(getString(R.string.pref_video_enable_key)))
            .setChecked(mPrefs.isVideoEnabled());
    ((CheckBoxPreference) findPreference(getString(R.string.pref_video_use_front_camera_key)))
            .setChecked(mPrefs.useFrontCam());
    ((CheckBoxPreference) findPreference(getString(R.string.pref_video_initiate_call_with_video_key)))
            .setChecked(mPrefs.shouldInitiateVideoCall());
    //((CheckBoxPreference) findPreference(getString(R.string.pref_video_automatically_share_my_video_key))).setChecked(mPrefs.shouldAutomaticallyShareMyVideo());
    ((CheckBoxPreference) findPreference(getString(R.string.pref_video_automatically_accept_video_key)))
            .setChecked(mPrefs.shouldAutomaticallyAcceptVideoRequests());
}

From source file:com.p3authentication.preferences.Prefs.java

@SuppressWarnings("deprecation")
@Override/* ww w .  j av  a 2  s  .  com*/
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    addPreferencesFromResource(R.xml.pref);

    AccessPin = (EditTextPreference) getPreferenceManager().findPreference("KeypadKey");
    final Preference ResetPreference = getPreferenceManager().findPreference("reset_data");
    final Preference EULAPreference = getPreferenceManager().findPreference("eula");
    final Preference AboutUsPreference = getPreferenceManager().findPreference("about_us");
    final Preference UnlockAppsPreference = getPreferenceManager().findPreference("unlock_apps");
    final Preference TouchTolerance = getPreferenceManager().findPreference("touch_tolerance");
    final Preference RedownloadImage = getPreferenceManager().findPreference("redownload_images");
    final Preference RateApp = getPreferenceManager().findPreference("rate_app");
    final CheckBoxPreference GhostStatusPref = (CheckBoxPreference) getPreferenceManager()
            .findPreference("GhostStatus");
    final CheckBoxPreference StartServicePref = (CheckBoxPreference) getPreferenceManager()
            .findPreference("startup_service");
    final ListPreference patterntype = (ListPreference) getPreferenceManager().findPreference("PatternType");
    final ListPreference PatternStealth = (ListPreference) getPreferenceManager()
            .findPreference("PatternStealth");
    if (patterntype.getValue().toString().equals("No Pattern")) {
        PatternStealth.setEnabled(false);
    } else {
        PatternStealth.setEnabled(true);
    }

    if (GhostStatusPref.isChecked()) {
        AccessPin.setEnabled(true);
    } else {
        AccessPin.setEnabled(false);
    }
    AccessPin.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            // TODO Auto-generated method stub
            if (newValue.toString().trim().equals("")) {

                Toast.makeText(Prefs.this, "Your Custom PIN cannot be empty.", Toast.LENGTH_LONG).show();

                return false;
            } else if (newValue.toString().length() < 5) {
                Toast.makeText(Prefs.this, "Your Custom PIN must be atleast 5 Digits.", Toast.LENGTH_LONG)
                        .show();

                return false;
            }
            Toast.makeText(Prefs.this, "Your Custom PIN is set.", Toast.LENGTH_LONG).show();
            return true;
        }

    });
    GhostStatusPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (newValue.toString().equals("true")) {
                hideLauncherIcon();
                Toast.makeText(Prefs.this, "P3 hidden from App Menu", Toast.LENGTH_SHORT).show();
            } else {
                showLauncherIcon();
                Toast.makeText(Prefs.this, "P3 visible on App Menu", Toast.LENGTH_SHORT).show();
            }
            return true;
        }

    });
    StartServicePref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (newValue.toString().equals("true")) {
                ComponentName receiver = new ComponentName(Prefs.this, Startup.class);
                PackageManager pm = getPackageManager();

                pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                        PackageManager.DONT_KILL_APP);

            } else {
                ComponentName receiver = new ComponentName(Prefs.this, Startup.class);
                PackageManager pm = getPackageManager();

                pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                        PackageManager.DONT_KILL_APP);
            }
            return true;
        }

    });
    patterntype.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            // TODO Auto-generated method stub
            if (!newValue.toString().equals("No Pattern")) {
                PatternStealth.setEnabled(true);
            } else {
                PatternStealth.setEnabled(false);
            }
            return true;
        }
    });
    ResetPreference.setOnPreferenceClickListener(this);
    UnlockAppsPreference.setOnPreferenceClickListener(this);
    TouchTolerance.setOnPreferenceClickListener(this);
    RedownloadImage.setOnPreferenceClickListener(this);
    RateApp.setOnPreferenceClickListener(this);
    AboutUsPreference.setOnPreferenceClickListener(this);
    EULAPreference.setOnPreferenceClickListener(this);

}

From source file:com.googlecode.mindbell.MindBellPreferences.java

@SuppressWarnings("deprecation") // deprecation is because MindBell is not fragment-based
@Override//from  www. j  a  v a 2  s  . co m
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // check settings, delete any settings that are not valid
    final PrefsAccessor prefs = ContextAccessor.getInstance(this).getPrefs();

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preferences_1);
    addPreferencesFromResource(R.xml.preferences_2); // notifications depend on SDK
    addPreferencesFromResource(R.xml.preferences_3);

    final CheckBoxPreference preferenceUseAudioStreamVolumeSetting = (CheckBoxPreference) getPreferenceScreen()
            .findPreference(getText(R.string.keyUseAudioStreamVolumeSetting));
    final CheckBoxPreference preferenceStatus = (CheckBoxPreference) getPreferenceScreen()
            .findPreference(getText(R.string.keyStatus));
    final CheckBoxPreference preferenceShow = (CheckBoxPreference) getPreferenceScreen()
            .findPreference(getText(R.string.keyShow));
    final CheckBoxPreference preferenceSound = (CheckBoxPreference) getPreferenceScreen()
            .findPreference(getText(R.string.keySound));
    final Preference preferenceReminderSoundLength = (Preference) getPreferenceScreen()
            .findPreference(getText(R.string.keyReminderSoundLength));
    final ListPreferenceWithSummaryFix preferenceReminderBell = (ListPreferenceWithSummaryFix) getPreferenceScreen()
            .findPreference(getText(R.string.keyReminderBell));
    final MediaVolumePreference preferenceVolume = (MediaVolumePreference) getPreferenceScreen()
            .findPreference(getText(R.string.keyVolume));
    final RingtonePreference preferenceRingtone = (RingtonePreference) getPreferenceScreen()
            .findPreference(getText(R.string.keyRingtone));
    final CheckBoxPreference preferenceVibrate = (CheckBoxPreference) getPreferenceScreen()
            .findPreference(getText(R.string.keyVibrate));
    final ListPreferenceWithSummaryFix preferencePattern = (ListPreferenceWithSummaryFix) getPreferenceScreen()
            .findPreference(getText(R.string.keyPattern));
    final CheckBoxPreference preferenceMuteOffHook = (CheckBoxPreference) getPreferenceScreen()
            .findPreference(getText(R.string.keyMuteOffHook));
    final MinutesIntervalPickerPreference preferenceFrequency = (MinutesIntervalPickerPreference) getPreferenceScreen()
            .findPreference(getText(R.string.keyFrequency));
    final CheckBoxPreference preferenceRandomize = (CheckBoxPreference) getPreferenceScreen()
            .findPreference(getText(R.string.keyRandomize));
    final ListPreferenceWithSummaryFix preferenceNormalize = (ListPreferenceWithSummaryFix) getPreferenceScreen()
            .findPreference(getText(R.string.keyNormalize));
    final MultiSelectListPreferenceWithSummary preferenceActiveOnDaysOfWeek = (MultiSelectListPreferenceWithSummary) getPreferenceScreen()
            .findPreference(getText(R.string.keyActiveOnDaysOfWeek));
    final MediaVolumePreference preferenceMeditationVolume = (MediaVolumePreference) getPreferenceScreen()
            .findPreference(getText(R.string.keyMeditationVolume));
    final CheckBoxPreference preferenceUseWorkaroundBell = (CheckBoxPreference) getPreferenceScreen()
            .findPreference(getText(R.string.keyUseWorkaroundBell));
    final Preference preferenceFAQ = (Preference) getPreferenceScreen()
            .findPreference(getText(R.string.keyFAQ));
    final Preference preferenceBatterySettings = (Preference) getPreferenceScreen()
            .findPreference(getText(R.string.keyBatterySettings));
    final Preference preferenceSendMail = (Preference) getPreferenceScreen()
            .findPreference(getText(R.string.keySendMail));

    preferenceUseAudioStreamVolumeSetting.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            boolean isChecked = (Boolean) newValue;
            if (!isChecked && prefs.mustUseAudioStreamVolumeSetting()) {
                Toast.makeText(MindBellPreferences.this, R.string.mustUseAudioStreamSetting, Toast.LENGTH_SHORT)
                        .show();
                return false;
            } else {
                preferenceVolume.setEnabled(preferenceSound.isChecked() && !isChecked);
                preferenceMeditationVolume.setEnabled(!isChecked);
                return true;
            }
        }

    });

    preferenceStatus.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            return mediateMuteOffHookAndStatus(preferenceMuteOffHook, newValue, REQUEST_CODE_STATUS);
        }

    });

    preferenceShow.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            return mediateShowAndSoundAndVibrate(preferenceSound, preferenceVibrate, newValue);
        }

    });

    preferenceSound.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (mediateShowAndSoundAndVibrate(preferenceShow, preferenceVibrate, newValue)
                    && mediateSoundDurationRelatedSettings(preferenceFrequency, preferenceUseWorkaroundBell,
                            preferenceReminderBell, preferenceRingtoneValue, newValue)) {
                boolean isChecked = (Boolean) newValue;
                preferenceReminderBell.setEnabled(isChecked);
                preferenceRingtone.setEnabled(
                        isChecked && !PrefsAccessor.isUseStandardBell(preferenceReminderBell.getValue()));
                preferenceVolume.setEnabled(!preferenceUseAudioStreamVolumeSetting.isChecked() && isChecked);
                return true;
            } else {
                return false;
            }
        }

    });

    preferenceReminderSoundLength.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            onPreferenceReminderSoundLength(preferenceUseWorkaroundBell.isChecked(),
                    preferenceReminderBell.getValue(), preferenceRingtoneValue);
            return true;
        }

    });

    preferenceReminderBell.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            String reminderBell = (String) newValue;
            boolean isChecked = PrefsAccessor.isUseStandardBell(reminderBell);
            if (PrefsAccessor.isUseStandardBell(reminderBell)
                    || ContextCompat.checkSelfPermission(MindBellPreferences.this,
                            Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                if (mediateSoundDurationRelatedSettings(preferenceFrequency, preferenceUseWorkaroundBell,
                        reminderBell, preferenceRingtoneValue, preferenceSound)) {
                    // Allow setting this option to "off" if permission is granted
                    preferenceRingtone.setEnabled(preferenceSound.isChecked() && !isChecked);
                    // Weird, but ringtone cannot be retrieved from RingtonePreference, only from SharedPreference
                    setPreferenceVolumeSoundUri(preferenceVolume, reminderBell,
                            preferenceUseWorkaroundBell.isChecked(), preferenceRingtoneValue);
                    return true;
                } else {
                    return false;
                }
            } else {
                // Ask for permission if this option shall be set to "off" but permission is missing
                ActivityCompat.requestPermissions(MindBellPreferences.this,
                        new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, REQUEST_CODE_RINGTONE);
                // As the permission request is asynchronous we have to deny setting this option (to "off")
                return false;
            }
        }

    });

    preferenceRingtone.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            String newRingtoneValue = (String) newValue;
            if (validatePreferenceRingtone(newRingtoneValue)
                    && mediateSoundDurationRelatedSettings(preferenceFrequency, preferenceUseWorkaroundBell,
                            preferenceReminderBell, newRingtoneValue, preferenceSound)) {
                setPreferenceRingtoneSummary(preferenceRingtone, newRingtoneValue);
                setPreferenceVolumeSoundUri(preferenceVolume, preferenceReminderBell.getValue(),
                        preferenceUseWorkaroundBell.isChecked(), newRingtoneValue);
                preferenceRingtoneValue = newRingtoneValue;
                return true;
            } else {
                return false;
            }
        }

    });

    preferenceVibrate.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            return mediateShowAndSoundAndVibrate(preferenceShow, preferenceSound, newValue);
        }

    });

    preferencePattern.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Vibrator vibrator = (Vibrator) MindBellPreferences.this.getSystemService(Context.VIBRATOR_SERVICE);
            vibrator.vibrate(PrefsAccessor.getVibrationPattern((String) newValue), -1);
            return true;
        }

    });

    preferenceMuteOffHook.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            return mediateMuteOffHookAndStatus(preferenceStatus, newValue, REQUEST_CODE_MUTE_OFF_HOOK);
        }

    });

    preferenceRandomize.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if ((Boolean) newValue) {
                // if interval deviation is selected, normalize is disabled on screen but it must be disabled in preferences,
                // too. Otherwise the following scenario could happen: set interval 1 h, de-select randomize, set normalize to
                // hh:00, select randomize, set interval 2 h, de-select randomize again ... hh:00 would be left in normalize
                // erroneously.
                preferenceNormalize.setValue(PrefsAccessor.NORMALIZE_NONE);
            }
            return true;
        }

    });

    preferenceFrequency.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (!mediateSoundDurationRelatedSettings(newValue, preferenceUseWorkaroundBell,
                    preferenceReminderBell, preferenceRingtoneValue, preferenceSound)) {
                return false;
            } else if (preferenceRandomize.isChecked()) {
                // if interval varies randomly, ringing on the minute is disabled and set to "no" anyway
                return true;
            } else if (isFrequencyDividesAnHour(new TimeOfDay((String) newValue))) {
                // if frequency is factor of an hour, ringing on the minute may be requested
                preferenceNormalize.setEnabled(true);
            } else {
                // if frequency is NOT factor of an hour, ringing on the minute may NOT be set
                if (preferenceNormalize.isEnabled() && isNormalize(preferenceNormalize.getValue())) {
                    Toast.makeText(MindBellPreferences.this, R.string.frequencyDoesNotFitIntoAnHour,
                            Toast.LENGTH_SHORT).show();
                    return false;
                } else {
                    preferenceNormalize.setEnabled(false);
                }
            }
            return true;
        }

    });

    preferenceNormalize.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (!isNormalize((String) newValue)) {
                // if normalize - ringing on the minute - is not wanted, it's fine, no more to check here
                return true;
            } else if (isFrequencyDividesAnHour(preferenceFrequency.getTime())) {
                // if frequency is factor of an hour, requesting ringing on the minute is allowed
                return true;
            } else {
                // if frequency is NOT factor of an hour, ringing on the minute may NOT be set
                Toast.makeText(MindBellPreferences.this, R.string.frequencyDoesNotFitIntoAnHour,
                        Toast.LENGTH_SHORT).show();
                return false;
            }
        }

    });

    preferenceActiveOnDaysOfWeek.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValues) {
            if (((Set<?>) newValues).isEmpty()) {
                Toast.makeText(MindBellPreferences.this, R.string.atLeastOneActiveDayNeeded, Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
            return true;
        }

    });

    preferenceFAQ.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            Uri faqUri = Uri.parse(getText(R.string.faq_url).toString());
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, faqUri);
            startActivity(browserIntent);
            return true;
        }

    });

    preferenceBatterySettings.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            onPreferenceClickBatterySettings();
            return true;
        }

    });

    preferenceUseWorkaroundBell.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (mediateSoundDurationRelatedSettings(preferenceFrequency, newValue, preferenceReminderBell,
                    preferenceRingtoneValue, preferenceSound)) {
                boolean isChecked = (Boolean) newValue;
                setPreferenceVolumeSoundUri(preferenceVolume, preferenceReminderBell.getValue(), isChecked,
                        preferenceRingtoneValue);
                return true;
            } else {
                return false;
            }
        }

    });

    preferenceSendMail.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            new AlertDialog.Builder(MindBellPreferences.this) //
                    .setTitle(R.string.prefsSendMail) //
                    .setMessage(R.string.mailInfo1) //
                    .setIcon(R.mipmap.ic_launcher) //
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            onClickReallySendInfo();
                        }
                    }) //
                    .setNegativeButton(android.R.string.cancel, null) //
                    .show();
            return true;
        }

    });

    // As no PreferenceChangeListener is called without change *BY USER*, some settings have to be made explicitly
    preferenceVolume
            .setEnabled(preferenceSound.isChecked() && !preferenceUseAudioStreamVolumeSetting.isChecked());
    preferenceMeditationVolume.setEnabled(!preferenceUseAudioStreamVolumeSetting.isChecked());
    preferenceReminderBell.setEnabled(preferenceSound.isChecked());
    preferenceRingtone.setEnabled(
            preferenceSound.isChecked() && !PrefsAccessor.isUseStandardBell(preferenceReminderBell.getValue()));
    preferenceRingtoneValue = prefs.getRingtone(); // cannot be retrieved from preference
    setPreferenceRingtoneSummary(preferenceRingtone, preferenceRingtoneValue);
    setPreferenceVolumeSoundUri(preferenceVolume, preferenceReminderBell.getValue(),
            preferenceUseWorkaroundBell.isChecked(), preferenceRingtoneValue);

}

From source file:im.vector.fragments.VectorSettingsPreferencesFragment.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final Context appContext = getActivity().getApplicationContext();

    // retrieve the arguments
    Bundle args = getArguments();/*  w w w.j  av a2 s .  c o  m*/
    String matrixId = args.getString(ARG_MATRIX_ID);
    mSession = Matrix.getInstance(appContext).getSession(matrixId);

    // sanity checks
    if ((null == mSession) || !mSession.isAlive()) {
        getActivity().finish();
        return;
    }

    // define the layout
    addPreferencesFromResource(R.xml.vector_settings_preferences);

    if (null == mPushesRuleByResourceId) {
        mPushesRuleByResourceId = new HashMap<>();

        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_ENABLE_ALL_NOTIF_PREFERENCE_KEY,
                BingRule.RULE_ID_DISABLE_ALL);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_ENABLE_THIS_DEVICE_PREFERENCE_KEY, DUMMY_RULE);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_TURN_SCREEN_ON_PREFERENCE_KEY, DUMMY_RULE);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_CONTAINING_MY_DISPLAY_NAME_PREFERENCE_KEY,
                BingRule.RULE_ID_CONTAIN_DISPLAY_NAME);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_CONTAINING_MY_USER_NAME_PREFERENCE_KEY,
                BingRule.RULE_ID_CONTAIN_USER_NAME);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_MESSAGES_IN_ONE_TO_ONE_PREFERENCE_KEY,
                BingRule.RULE_ID_ONE_TO_ONE_ROOM);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_MESSAGES_IN_GROUP_CHAT_PREFERENCE_KEY,
                BingRule.RULE_ID_ALL_OTHER_MESSAGES_ROOMS);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_INVITED_TO_ROOM_PREFERENCE_KEY,
                BingRule.RULE_ID_INVITE_ME);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_CALL_INVITATIONS_PREFERENCE_KEY,
                BingRule.RULE_ID_CALL);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_MESSAGES_SENT_BY_BOT_PREFERENCE_KEY,
                BingRule.RULE_ID_SUPPRESS_BOTS_NOTIFICATIONS);
    }

    UserAvatarPreference avatarPreference = (UserAvatarPreference) findPreference(
            PreferencesManager.SETTINGS_PROFILE_PICTURE_PREFERENCE_KEY);
    avatarPreference.setSession(mSession);
    avatarPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            onUpdateAvatarClick();
            return false;
        }
    });

    EditTextPreference passwordPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_CHANGE_PASSWORD_PREFERENCE_KEY);
    passwordPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            onPasswordUpdateClick();
            return false;
        }
    });

    EditTextPreference notificationRingTonePreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATION_RINGTONE_SELECTION_PREFERENCE_KEY);
    notificationRingTonePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);

            if (null != PreferencesManager.getNotificationRingTone(getActivity())) {
                intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI,
                        PreferencesManager.getNotificationRingTone(getActivity()));
            }
            getActivity().startActivityForResult(intent, REQUEST_NOTIFICATION_RINGTONE);
            return false;
        }
    });
    refreshNotificationRingTone();

    EditTextPreference notificationPrivacyPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATION_PRIVACY_PREFERENCE_KEY);
    if (notificationPrivacyPreference != null) {
        notificationPrivacyPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivity(NotificationPrivacyActivity.getIntent(getActivity()));
                return true;
            }
        });
        refreshNotificationPrivacy();
    }

    // application version
    VectorCustomActionEditTextPreference versionTextPreference = (VectorCustomActionEditTextPreference) findPreference(
            PreferencesManager.SETTINGS_VERSION_PREFERENCE_KEY);
    if (null != versionTextPreference) {
        versionTextPreference.setSummary(VectorUtils.getApplicationVersion(appContext));

        versionTextPreference.setOnPreferenceLongClickListener(
                new VectorCustomActionEditTextPreference.OnPreferenceLongClickListener() {
                    @Override
                    public boolean onPreferenceLongClick(Preference preference) {
                        VectorUtils.copyToClipboard(appContext, VectorUtils.getApplicationVersion(appContext));
                        return true;
                    }
                });
    }

    // olm version
    EditTextPreference olmTextPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_OLM_VERSION_PREFERENCE_KEY);
    if (null != olmTextPreference) {
        olmTextPreference.setSummary(
                Matrix.getInstance(appContext).getDefaultSession().getCryptoVersion(appContext, false));
    }

    // user account
    EditTextPreference accountIdTextPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_LOGGED_IN_PREFERENCE_KEY);
    if (null != accountIdTextPreference) {
        accountIdTextPreference.setSummary(mSession.getMyUserId());
    }

    // home server
    EditTextPreference homeServerTextPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_HOME_SERVER_PREFERENCE_KEY);
    if (null != homeServerTextPreference) {
        homeServerTextPreference.setSummary(mSession.getHomeServerConfig().getHomeserverUri().toString());
    }

    // identity server
    EditTextPreference identityServerTextPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_IDENTITY_SERVER_PREFERENCE_KEY);
    if (null != identityServerTextPreference) {
        identityServerTextPreference
                .setSummary(mSession.getHomeServerConfig().getIdentityServerUri().toString());
    }

    // terms & conditions
    EditTextPreference termConditionsPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_APP_TERM_CONDITIONS_PREFERENCE_KEY);

    if (null != termConditionsPreference) {
        termConditionsPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                VectorUtils.displayAppTac();
                return false;
            }
        });
    }

    // Themes
    ListPreference themePreference = (ListPreference) findPreference(ThemeUtils.APPLICATION_THEME_KEY);

    if (null != themePreference) {
        themePreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                if (newValue instanceof String) {
                    VectorApp.updateApplicationTheme((String) newValue);
                    getActivity().startActivity(getActivity().getIntent());
                    getActivity().finish();
                    return true;
                } else {
                    return false;
                }
            }
        });
    }

    // privacy policy
    EditTextPreference privacyPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_PRIVACY_POLICY_PREFERENCE_KEY);

    if (null != privacyPreference) {
        privacyPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                VectorUtils.displayAppPrivacyPolicy();
                return false;
            }
        });
    }

    // third party notice
    EditTextPreference thirdPartyNotices = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_THIRD_PARTY_NOTICES_PREFERENCE_KEY);

    if (null != thirdPartyNotices) {
        thirdPartyNotices.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                VectorUtils.displayThirdPartyLicenses();
                return false;
            }
        });
    }

    // copyright
    EditTextPreference copyrightNotices = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_COPYRIGHT_PREFERENCE_KEY);

    if (null != copyrightNotices) {
        copyrightNotices.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                VectorUtils.displayAppCopyright();
                return false;
            }
        });
    }

    // update keep medias period
    final EditTextPreference keepMediaPeriodPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_MEDIA_SAVING_PERIOD_KEY);

    if (null != keepMediaPeriodPreference) {
        keepMediaPeriodPreference
                .setSummary(PreferencesManager.getSelectedMediasSavingPeriodString(getActivity()));

        keepMediaPeriodPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                new AlertDialog.Builder(getActivity())
                        .setSingleChoiceItems(PreferencesManager.getMediasSavingItemsChoicesList(getActivity()),
                                PreferencesManager.getSelectedMediasSavingPeriod(getActivity()),
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface d, int n) {
                                        PreferencesManager.setSelectedMediasSavingPeriod(getActivity(), n);
                                        d.cancel();

                                        keepMediaPeriodPreference.setSummary(PreferencesManager
                                                .getSelectedMediasSavingPeriodString(getActivity()));
                                    }
                                })
                        .show();
                return false;
            }
        });
    }

    // clear medias cache
    final EditTextPreference clearMediaCachePreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_CLEAR_MEDIA_CACHE_PREFERENCE_KEY);

    if (null != clearMediaCachePreference) {
        MXMediasCache.getCachesSize(getActivity(), new SimpleApiCallback<Long>() {
            @Override
            public void onSuccess(Long size) {
                if (null != getActivity()) {
                    clearMediaCachePreference
                            .setSummary(android.text.format.Formatter.formatFileSize(getActivity(), size));
                }
            }
        });

        clearMediaCachePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                displayLoadingView();

                AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        mSession.getMediasCache().clear();
                        Glide.get(getActivity()).clearDiskCache();
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        hideLoadingView();

                        MXMediasCache.getCachesSize(getActivity(), new SimpleApiCallback<Long>() {
                            @Override
                            public void onSuccess(Long size) {
                                clearMediaCachePreference.setSummary(
                                        android.text.format.Formatter.formatFileSize(getActivity(), size));
                            }
                        });
                    }
                };

                try {
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## mSession.getMediasCache().clear() failed " + e.getMessage());
                    task.cancel(true);
                    hideLoadingView();
                }
                return false;
            }
        });
    }

    // clear cache
    final EditTextPreference clearCachePreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_CLEAR_CACHE_PREFERENCE_KEY);

    if (null != clearCachePreference) {
        MXSession.getApplicationSizeCaches(getActivity(), new SimpleApiCallback<Long>() {
            @Override
            public void onSuccess(Long size) {
                if (null != getActivity()) {
                    clearCachePreference
                            .setSummary(android.text.format.Formatter.formatFileSize(getActivity(), size));
                }
            }
        });

        clearCachePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                displayLoadingView();
                Matrix.getInstance(appContext).reloadSessions(appContext);
                return false;
            }
        });
    }

    final EditTextPreference displaynamePref = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_DISPLAY_NAME_PREFERENCE_KEY);
    displaynamePref.setSummary(mSession.getMyUser().displayname);
    displaynamePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            onDisplayNameClick((null == newValue) ? null : ((String) newValue).trim());
            return false;
        }
    });

    final VectorSwitchPreference urlPreviewPreference = (VectorSwitchPreference) findPreference(
            PreferencesManager.SETTINGS_SHOW_URL_PREVIEW_KEY);
    urlPreviewPreference.setChecked(mSession.isURLPreviewEnabled());

    urlPreviewPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {

            if ((null != newValue) && ((boolean) newValue != mSession.isURLPreviewEnabled())) {
                displayLoadingView();
                mSession.setURLPreviewStatus((boolean) newValue, new ApiCallback<Void>() {
                    @Override
                    public void onSuccess(Void info) {
                        urlPreviewPreference.setChecked(mSession.isURLPreviewEnabled());
                        hideLoadingView();
                    }

                    private void onError(String errorMessage) {
                        if (null != getActivity()) {
                            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
                        }
                        onSuccess(null);
                    }

                    @Override
                    public void onNetworkError(Exception e) {
                        onError(e.getLocalizedMessage());
                    }

                    @Override
                    public void onMatrixError(MatrixError e) {
                        onError(e.getLocalizedMessage());
                    }

                    @Override
                    public void onUnexpectedError(Exception e) {
                        onError(e.getLocalizedMessage());
                    }
                });
            }

            return false;
        }
    });

    // push rules
    for (String resourceText : mPushesRuleByResourceId.keySet()) {
        final Preference preference = findPreference(resourceText);

        if (null != preference) {
            if (preference instanceof CheckBoxPreference) {
                preference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                    @Override
                    public boolean onPreferenceChange(Preference preference, Object newValueAsVoid) {
                        // on some old android APIs,
                        // the callback is called even if there is no user interaction
                        // so the value will be checked to ensure there is really no update.
                        onPushRuleClick(preference.getKey(), (boolean) newValueAsVoid);
                        return true;
                    }
                });
            } else if (preference instanceof BingRulePreference) {
                final BingRulePreference bingRulePreference = (BingRulePreference) preference;
                bingRulePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference preference) {
                        new AlertDialog.Builder(getActivity()).setSingleChoiceItems(
                                bingRulePreference.getBingRuleStatuses(),
                                bingRulePreference.getRuleStatusIndex(), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface d, int index) {
                                        BingRule rule = bingRulePreference.createRule(index);
                                        d.cancel();

                                        if (null != rule) {
                                            displayLoadingView();
                                            mSession.getDataHandler().getBingRulesManager().updateRule(
                                                    bingRulePreference.getRule(), rule,
                                                    new BingRulesManager.onBingRuleUpdateListener() {
                                                        private void onDone() {
                                                            refreshDisplay();
                                                            hideLoadingView();
                                                        }

                                                        @Override
                                                        public void onBingRuleUpdateSuccess() {
                                                            onDone();
                                                        }

                                                        @Override
                                                        public void onBingRuleUpdateFailure(
                                                                String errorMessage) {
                                                            if (null != getActivity()) {
                                                                Toast.makeText(getActivity(), errorMessage,
                                                                        Toast.LENGTH_SHORT).show();
                                                            }
                                                            onDone();
                                                        }
                                                    });
                                        }
                                    }
                                }).show();
                        return true;
                    }
                });
            }
        }
    }

    // background sync tuning settings
    // these settings are useless and hidden if the app is registered to the GCM push service
    final GcmRegistrationManager gcmMgr = Matrix.getInstance(appContext).getSharedGCMRegistrationManager();
    if (gcmMgr.useGCM() && gcmMgr.hasRegistrationToken()) {
        // Hide the section
        PreferenceScreen preferenceScreen = getPreferenceScreen();
        PreferenceCategory backgroundSyncCategory = (PreferenceCategory) findPreference(
                PreferencesManager.SETTINGS_BACKGROUND_SYNC_PREFERENCE_KEY);
        PreferenceCategory backgroundSyncDivider = (PreferenceCategory) findPreference(
                PreferencesManager.SETTINGS_BACKGROUND_SYNC_DIVIDER_PREFERENCE_KEY);

        preferenceScreen.removePreference(backgroundSyncDivider);
        preferenceScreen.removePreference(backgroundSyncCategory);
    } else {
        mSyncRequestTimeoutPreference = (EditTextPreference) findPreference(
                PreferencesManager.SETTINGS_SET_SYNC_TIMEOUT_PREFERENCE_KEY);
        mSyncRequestDelayPreference = (EditTextPreference) findPreference(
                PreferencesManager.SETTINGS_SET_SYNC_DELAY_PREFERENCE_KEY);
        final CheckBoxPreference useBackgroundSyncPref = (CheckBoxPreference) findPreference(
                PreferencesManager.SETTINGS_ENABLE_BACKGROUND_SYNC_PREFERENCE_KEY);

        if (null != useBackgroundSyncPref) {

            final GcmRegistrationManager.ThirdPartyRegistrationListener listener = new GcmRegistrationManager.ThirdPartyRegistrationListener() {

                @Override
                public void onThirdPartyRegistered() {
                    hideLoadingView();
                }

                @Override
                public void onThirdPartyRegistrationFailed() {
                    hideLoadingView();
                }

                @Override
                public void onThirdPartyUnregistered() {
                    hideLoadingView();
                }

                @Override
                public void onThirdPartyUnregistrationFailed() {
                    hideLoadingView();
                }
            };

            if (null != useBackgroundSyncPref) {
                useBackgroundSyncPref.setChecked(gcmMgr.isBackgroundSyncAllowed());

                useBackgroundSyncPref
                        .setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                            @Override
                            public boolean onPreferenceChange(Preference preference, Object aNewValue) {
                                final boolean newValue = (boolean) aNewValue;

                                if (newValue != gcmMgr.isBackgroundSyncAllowed()) {
                                    gcmMgr.setBackgroundSyncAllowed(newValue);
                                }

                                displayLoadingView();

                                Matrix.getInstance(VectorSettingsPreferencesFragment.this.getActivity())
                                        .getSharedGCMRegistrationManager().forceSessionsRegistration(listener);

                                return true;
                            }
                        });
            }
        }
    }

    mUserSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_USER_SETTINGS_PREFERENCE_KEY);
    mContactSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_CONTACT_PREFERENCE_KEYS);
    mPushersSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATIONS_TARGETS_PREFERENCE_KEY);
    mPushersSettingsDivider = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATIONS_TARGET_DIVIDER_PREFERENCE_KEY);
    mIgnoredUserSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_IGNORED_USERS_PREFERENCE_KEY);
    mIgnoredUserSettingsCategoryDivider = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_IGNORE_USERS_DIVIDER_PREFERENCE_KEY);
    mDevicesListSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_DEVICES_LIST_PREFERENCE_KEY);
    mDevicesListSettingsCategoryDivider = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_DEVICES_DIVIDER_PREFERENCE_KEY);
    mCryptographyCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_CRYPTOGRAPHY_PREFERENCE_KEY);
    mCryptographyCategoryDivider = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_CRYPTOGRAPHY_DIVIDER_PREFERENCE_KEY);
    mLabsCategory = (PreferenceCategory) findPreference(PreferencesManager.SETTINGS_LABS_PREFERENCE_KEY);
    mGroupsFlairCategory = (PreferenceCategory) findPreference(PreferencesManager.SETTINGS_GROUPS_FLAIR_KEY);

    // preference to start the App info screen, to facilitate App permissions access
    Preference applicationInfoLInkPref = findPreference(APP_INFO_LINK_PREFERENCE_KEY);
    applicationInfoLInkPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (null != getActivity()) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri uri = Uri.fromParts("package", appContext.getPackageName(), null);
                intent.setData(uri);
                getActivity().getApplicationContext().startActivity(intent);
            }

            return true;
        }
    });

    // Contacts
    setContactsPreferences();

    // user interface preferences
    setUserInterfacePreferences();

    final CheckBoxPreference useCryptoPref = (CheckBoxPreference) findPreference(
            PreferencesManager.SETTINGS_ROOM_SETTINGS_LABS_END_TO_END_PREFERENCE_KEY);
    final Preference cryptoIsEnabledPref = findPreference(
            PreferencesManager.SETTINGS_ROOM_SETTINGS_LABS_END_TO_END_IS_ACTIVE_PREFERENCE_KEY);

    cryptoIsEnabledPref.setEnabled(false);

    if (!mSession.isCryptoEnabled()) {
        useCryptoPref.setChecked(false);
        mLabsCategory.removePreference(cryptoIsEnabledPref);
    } else {
        mLabsCategory.removePreference(useCryptoPref);
    }

    useCryptoPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValueAsVoid) {
            if (TextUtils.isEmpty(mSession.getCredentials().deviceId)) {
                new AlertDialog.Builder(getActivity())
                        .setMessage(R.string.room_settings_labs_end_to_end_warnings)
                        .setPositiveButton(R.string.logout, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                CommonActivityUtils.logout(getActivity());

                            }
                        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                useCryptoPref.setChecked(false);
                            }
                        }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                dialog.dismiss();
                                useCryptoPref.setChecked(false);
                            }
                        }).create().show();
            } else {
                boolean newValue = (boolean) newValueAsVoid;

                if (mSession.isCryptoEnabled() != newValue) {
                    displayLoadingView();

                    mSession.enableCrypto(newValue, new ApiCallback<Void>() {
                        private void refresh() {
                            if (null != getActivity()) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        hideLoadingView();
                                        useCryptoPref.setChecked(mSession.isCryptoEnabled());

                                        if (mSession.isCryptoEnabled()) {
                                            mLabsCategory.removePreference(useCryptoPref);
                                            mLabsCategory.addPreference(cryptoIsEnabledPref);
                                        }
                                    }
                                });
                            }
                        }

                        @Override
                        public void onSuccess(Void info) {
                            useCryptoPref.setEnabled(false);
                            refresh();
                        }

                        @Override
                        public void onNetworkError(Exception e) {
                            useCryptoPref.setChecked(false);
                        }

                        @Override
                        public void onMatrixError(MatrixError e) {
                            useCryptoPref.setChecked(false);
                        }

                        @Override
                        public void onUnexpectedError(Exception e) {
                            useCryptoPref.setChecked(false);
                        }
                    });
                }
            }

            return true;
        }
    });

    // SaveMode Managment
    final CheckBoxPreference dataSaveModePref = (CheckBoxPreference) findPreference(
            PreferencesManager.SETTINGS_DATA_SAVE_MODE_PREFERENCE_KEY);
    dataSaveModePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            List<MXSession> sessions = Matrix.getMXSessions(getActivity());
            for (MXSession session : sessions) {
                session.setUseDataSaveMode((boolean) newValue);
            }

            return true;
        }
    });

    // Analytics tracking managment
    final CheckBoxPreference useAnalyticsModePref = (CheckBoxPreference) findPreference(
            PreferencesManager.SETTINGS_USE_ANALYTICS_KEY);

    // On if the analytics tracking is activated
    useAnalyticsModePref.setChecked(PreferencesManager.useAnalytics(appContext));

    useAnalyticsModePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            PreferencesManager.setUseAnalytics(appContext, (boolean) newValue);
            return true;
        }
    });

    // Rageshake Managment
    final CheckBoxPreference useRageShakeModePref = (CheckBoxPreference) findPreference(
            PreferencesManager.SETTINGS_USE_RAGE_SHAKE_KEY);
    final boolean mIsUsedRageShake = PreferencesManager.useRageshake(appContext);

    useRageShakeModePref.setChecked(mIsUsedRageShake);

    useRageShakeModePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            PreferencesManager.setUseRageshake(appContext, (boolean) newValue);
            return true;
        }
    });

    // deactivate account
    EditTextPreference deactivateAccountPref = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_DEACTIVATE_ACCOUNT_KEY);

    if (null != deactivateAccountPref) {
        deactivateAccountPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivity(DeactivateAccountActivity.Companion.getIntent(getActivity()));

                return false;
            }
        });
    }

    addButtons();
    refreshPushersList();
    refreshEmailsList();
    refreshPhoneNumbersList();
    refreshIgnoredUsersList();
    refreshDevicesList();
    refreshGroupFlairsList();
}