Example usage for android.preference EditTextPreference setSummary

List of usage examples for android.preference EditTextPreference setSummary

Introduction

In this page you can find the example usage for android.preference EditTextPreference setSummary.

Prototype

public void setSummary(CharSequence summary) 

Source Link

Document

Sets the summary for this Preference with a CharSequence.

Usage

From source file:com.aware.Aware_Preferences.java

/**
 * Temperature module settings UI//from ww w  .  j a  v a  2  s. c o m
 */
private void temperature() {
    final PreferenceScreen temp_pref = (PreferenceScreen) findPreference("temperature");
    Sensor temp = mSensorMgr.getDefaultSensor(Sensor.TYPE_TEMPERATURE);
    if (temp != null) {
        temp_pref.setSummary(
                temp_pref.getSummary().toString().replace("*", " - Power: " + temp.getPower() + " mA"));
    } else {
        temp_pref.setSummary(temp_pref.getSummary().toString().replace("*", ""));
    }

    final CheckBoxPreference temperature = (CheckBoxPreference) findPreference(
            Aware_Preferences.STATUS_TEMPERATURE);
    temperature.setChecked(
            Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_TEMPERATURE).equals("true"));
    temperature.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (mSensorMgr.getDefaultSensor(Sensor.TYPE_TEMPERATURE) == null) {
                showDialog(DIALOG_ERROR_MISSING_SENSOR);
                temperature.setChecked(false);
                Aware.setSetting(getApplicationContext(), Aware_Preferences.STATUS_TEMPERATURE, false);
                return false;
            }

            Aware.setSetting(getApplicationContext(), Aware_Preferences.STATUS_TEMPERATURE,
                    temperature.isChecked());
            if (temperature.isChecked()) {
                framework.startTemperature();
            } else {
                framework.stopTemperature();
            }
            return true;
        }
    });

    final EditTextPreference frequency_temperature = (EditTextPreference) findPreference(
            Aware_Preferences.FREQUENCY_TEMPERATURE);
    frequency_temperature
            .setText(Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_TEMPERATURE));
    if (Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_TEMPERATURE).length() > 0) {
        frequency_temperature
                .setSummary(Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_TEMPERATURE)
                        + " microseconds");
    }
    frequency_temperature.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Aware.setSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_TEMPERATURE,
                    (String) newValue);
            frequency_temperature.setSummary((String) newValue + " microseconds");
            framework.startTemperature();
            return true;
        }
    });
}

From source file:com.aware.Aware_Preferences.java

/**
 * Webservices module settings UI//from   w ww.j  ava2 s.  c o  m
 */
private void webservices() {
    final CheckBoxPreference webservice = (CheckBoxPreference) findPreference(
            Aware_Preferences.STATUS_WEBSERVICE);
    webservice.setChecked(
            Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_WEBSERVICE).equals("true"));
    webservice.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {

            if (Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER).length() == 0) {
                showDialog(DIALOG_ERROR_MISSING_PARAMETERS);
                Aware.setSetting(getApplicationContext(), Aware_Preferences.STATUS_WEBSERVICE, false);
                webservice.setChecked(false);
                return false;
            } else {
                Aware.setSetting(getApplicationContext(), Aware_Preferences.STATUS_WEBSERVICE,
                        webservice.isChecked());
                if (webservice.isChecked()
                        && Aware.getSetting(getApplicationContext(), WEBSERVICE_SERVER).length() > 0) {
                    //setup and send data
                    Intent study_config = new Intent(getApplicationContext(), StudyConfig.class);
                    study_config.putExtra("study_url",
                            Aware.getSetting(getApplicationContext(), WEBSERVICE_SERVER));
                    startService(study_config);
                }
                return true;
            }
        }
    });

    final EditTextPreference webservice_server = (EditTextPreference) findPreference(
            Aware_Preferences.WEBSERVICE_SERVER);
    webservice_server.setText(Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER));
    if (Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER).length() > 0) {
        webservice_server.setSummary(
                "Server: " + Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER));
    }
    webservice_server.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Aware.setSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER, (String) newValue);
            webservice_server.setSummary("Server: " + (String) newValue);
            return true;
        }
    });

    final CheckBoxPreference webservice_wifi_only = (CheckBoxPreference) findPreference(
            Aware_Preferences.WEBSERVICE_WIFI_ONLY);
    webservice_wifi_only.setChecked(
            Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_WIFI_ONLY).equals("true"));
    webservice_wifi_only.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Aware.setSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_WIFI_ONLY,
                    webservice_wifi_only.isChecked());
            return true;
        }
    });

    final EditTextPreference frequency_webservice = (EditTextPreference) findPreference(
            Aware_Preferences.FREQUENCY_WEBSERVICE);
    if (Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_WEBSERVICE).length() > 0) {
        frequency_webservice.setSummary(
                Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_WEBSERVICE) + " minutes");
    }
    frequency_webservice
            .setText(Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_WEBSERVICE));
    frequency_webservice.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Aware.setSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_WEBSERVICE,
                    (String) newValue);
            frequency_webservice.setSummary((String) newValue + " minutes");
            return true;
        }
    });

    final ListPreference clean_old_data = (ListPreference) findPreference(FREQUENCY_CLEAN_OLD_DATA);
    if (Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_CLEAN_OLD_DATA).length() > 0) {
        String freq = Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_CLEAN_OLD_DATA);
        if (freq.equals("0")) {
            clean_old_data.setSummary("Never");
        } else if (freq.equals("1")) {
            clean_old_data.setSummary("Weekly");
        } else if (freq.equals("2")) {
            clean_old_data.setSummary("Monthly");
        }
    }
    clean_old_data.setDefaultValue(Aware.getSetting(getApplicationContext(), FREQUENCY_CLEAN_OLD_DATA));
    clean_old_data.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Aware.setSetting(getApplicationContext(), FREQUENCY_CLEAN_OLD_DATA, (String) newValue);
            if (((String) newValue).equals("0")) {
                clean_old_data.setSummary("Never");
            } else if (((String) newValue).equals("1")) {
                clean_old_data.setSummary("Weekly");
            } else if (((String) newValue).equals("2")) {
                clean_old_data.setSummary("Monthly");
            }
            return true;
        }
    });
}

From source file:com.master.metehan.filtereagle.ActivitySettings.java

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    final PreferenceScreen screen = getPreferenceScreen();
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    PreferenceCategory cat_options = (PreferenceCategory) screen.findPreference("category_options");
    PreferenceCategory cat_advanced = (PreferenceCategory) screen.findPreference("category_advanced_options");
    PreferenceCategory cat_backup = (PreferenceCategory) screen.findPreference("category_backup");
    PreferenceCategory cat_development = (PreferenceCategory) screen.findPreference("category_development");

    // Handle auto enable
    Preference pref_auto_enable = screen.findPreference("auto_enable");
    pref_auto_enable.setTitle(getString(R.string.setting_auto, prefs.getString("auto_enable", "0")));

    // Handle screen delay
    Preference pref_screen_delay = screen.findPreference("screen_delay");
    pref_screen_delay.setTitle(getString(R.string.setting_delay, prefs.getString("screen_delay", "0")));

    // Handle theme
    Preference pref_screen_theme = screen.findPreference("theme");
    String theme = prefs.getString("theme", "teal");
    String[] themeNames = getResources().getStringArray(R.array.themeNames);
    String[] themeValues = getResources().getStringArray(R.array.themeValues);
    for (int i = 0; i < themeNames.length; i++)
        if (theme.equals(themeValues[i])) {
            pref_screen_theme.setTitle(getString(R.string.setting_theme, themeNames[i]));
            break;
        }/* w ww. j  av  a  2s.  c om*/

    // Wi-Fi home
    MultiSelectListPreference pref_wifi_homes = (MultiSelectListPreference) screen.findPreference("wifi_homes");
    Set<String> ssid = prefs.getStringSet("wifi_homes", new HashSet<String>());
    if (ssid.size() > 0)
        pref_wifi_homes.setTitle(getString(R.string.setting_wifi_home, TextUtils.join(", ", ssid)));
    else
        pref_wifi_homes.setTitle(getString(R.string.setting_wifi_home, "-"));

    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    List<CharSequence> listSSID = new ArrayList<>();
    List<WifiConfiguration> configs = wm.getConfiguredNetworks();
    if (configs != null)
        for (WifiConfiguration config : configs)
            listSSID.add(config.SSID == null ? "NULL" : config.SSID);
    pref_wifi_homes.setEntries(listSSID.toArray(new CharSequence[0]));
    pref_wifi_homes.setEntryValues(listSSID.toArray(new CharSequence[0]));

    // Filtering always enabled
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        cat_advanced.removePreference(screen.findPreference("filter"));

    Preference pref_reset_usage = screen.findPreference("reset_usage");
    pref_reset_usage.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Util.areYouSure(ActivitySettings.this, R.string.setting_reset_usage, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    new AsyncTask<Object, Object, Throwable>() {
                        @Override
                        protected Throwable doInBackground(Object... objects) {
                            try {
                                DatabaseHelper.getInstance(ActivitySettings.this).resetUsage(-1);
                                return null;
                            } catch (Throwable ex) {
                                return ex;
                            }
                        }

                        @Override
                        protected void onPostExecute(Throwable ex) {
                            if (ex == null)
                                Toast.makeText(ActivitySettings.this, R.string.msg_completed, Toast.LENGTH_LONG)
                                        .show();
                            else
                                Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
                        }
                    }.execute();
                }
            });
            return false;
        }
    });

    // Handle port forwarding
    Preference pref_forwarding = screen.findPreference("forwarding");
    pref_forwarding.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivity(new Intent(ActivitySettings.this, ActivityForwarding.class));
            return true;
        }
    });

    // VPN parameters
    screen.findPreference("vpn4")
            .setTitle(getString(R.string.setting_vpn4, prefs.getString("vpn4", "10.1.10.1")));
    screen.findPreference("vpn6")
            .setTitle(getString(R.string.setting_vpn6, prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1")));
    EditTextPreference pref_dns = (EditTextPreference) screen.findPreference("dns");
    List<String> def_dns = Util.getDefaultDNS(this);
    pref_dns.getEditText().setHint(def_dns.get(0));
    pref_dns.setTitle(getString(R.string.setting_dns, prefs.getString("dns", def_dns.get(0))));

    // PCAP parameters
    screen.findPreference("pcap_record_size")
            .setTitle(getString(R.string.setting_pcap_record_size, prefs.getString("pcap_record_size", "64")));
    screen.findPreference("pcap_file_size")
            .setTitle(getString(R.string.setting_pcap_file_size, prefs.getString("pcap_file_size", "2")));

    // Handle stats
    EditTextPreference pref_stats_frequency = (EditTextPreference) screen.findPreference("stats_frequency");
    EditTextPreference pref_stats_samples = (EditTextPreference) screen.findPreference("stats_samples");
    pref_stats_frequency
            .setTitle(getString(R.string.setting_stats_frequency, prefs.getString("stats_frequency", "1000")));
    pref_stats_samples
            .setTitle(getString(R.string.setting_stats_samples, prefs.getString("stats_samples", "90")));

    // Handle export
    Preference pref_export = screen.findPreference("export");
    pref_export.setEnabled(getIntentCreateExport().resolveActivity(getPackageManager()) != null);
    pref_export.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(getIntentCreateExport(), ActivitySettings.REQUEST_EXPORT);
            return true;
        }
    });

    // Handle import
    Preference pref_import = screen.findPreference("import");
    pref_import.setEnabled(getIntentOpenExport().resolveActivity(getPackageManager()) != null);
    pref_import.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(getIntentOpenExport(), ActivitySettings.REQUEST_IMPORT);
            return true;
        }
    });

    // Hosts file settings
    Preference pref_block_domains = screen.findPreference("use_hosts");
    Preference pref_hosts_import = screen.findPreference("hosts_import");
    EditTextPreference pref_hosts_url = (EditTextPreference) screen.findPreference("hosts_url");
    final Preference pref_hosts_download = screen.findPreference("hosts_download");

    if (Util.isPlayStoreInstall(this)) {
        cat_options.removePreference(screen.findPreference("update_check"));
        cat_advanced.removePreference(pref_block_domains);
        cat_advanced.removePreference(pref_forwarding);
        cat_backup.removePreference(pref_hosts_import);
        cat_backup.removePreference(pref_hosts_url);
        cat_backup.removePreference(pref_hosts_download);

    } else {
        pref_block_domains.setEnabled(new File(getFilesDir(), "hosts.txt").exists());

        String last_import = prefs.getString("hosts_last_import", null);
        String last_download = prefs.getString("hosts_last_download", null);
        if (last_import != null)
            pref_hosts_import.setSummary(getString(R.string.msg_import_last, last_import));
        if (last_download != null)
            pref_hosts_download.setSummary(getString(R.string.msg_download_last, last_download));

        // Handle hosts import
        // https://github.com/Free-Software-for-Android/AdAway/wiki/HostsSources
        pref_hosts_import.setEnabled(getIntentOpenHosts().resolveActivity(getPackageManager()) != null);
        pref_hosts_import.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivityForResult(getIntentOpenHosts(), ActivitySettings.REQUEST_HOSTS);
                return true;
            }
        });

        // Handle hosts file download
        pref_hosts_url.setSummary(pref_hosts_url.getText());
        pref_hosts_download.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                final File tmp = new File(getFilesDir(), "hosts.tmp");
                final File hosts = new File(getFilesDir(), "hosts.txt");
                EditTextPreference pref_hosts_url = (EditTextPreference) screen.findPreference("hosts_url");
                try {
                    new DownloadTask(ActivitySettings.this, new URL(pref_hosts_url.getText()), tmp,
                            new DownloadTask.Listener() {
                                @Override
                                public void onCompleted() {
                                    if (hosts.exists())
                                        hosts.delete();
                                    tmp.renameTo(hosts);

                                    String last = SimpleDateFormat.getDateTimeInstance()
                                            .format(new Date().getTime());
                                    prefs.edit().putString("hosts_last_download", last).apply();

                                    if (running) {
                                        getPreferenceScreen().findPreference("use_hosts").setEnabled(true);
                                        pref_hosts_download
                                                .setSummary(getString(R.string.msg_download_last, last));
                                        Toast.makeText(ActivitySettings.this, R.string.msg_downloaded,
                                                Toast.LENGTH_LONG).show();
                                    }

                                    ServiceSinkhole.reload("hosts file download", ActivitySettings.this);
                                }

                                @Override
                                public void onCancelled() {
                                    if (tmp.exists())
                                        tmp.delete();
                                }

                                @Override
                                public void onException(Throwable ex) {
                                    if (tmp.exists())
                                        tmp.delete();

                                    if (running)
                                        Toast.makeText(ActivitySettings.this, ex.getMessage(),
                                                Toast.LENGTH_LONG).show();
                                }
                            }).execute();
                } catch (MalformedURLException ex) {
                    Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
                }
                return true;
            }
        });
    }

    // Development
    Preference pref_show_resolved = screen.findPreference("show_resolved");
    if (!(Util.isDebuggable(this) || Util.getSelfVersionName(this).contains("beta"))) {
        screen.removePreference(cat_development);
        prefs.edit().remove("loglevel").apply();
    } else if (!Util.isDebuggable(this))
        cat_development.removePreference(pref_show_resolved);

    // Show resolved
    pref_show_resolved.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivity(new Intent(ActivitySettings.this, ActivityDns.class));
            return true;
        }
    });

    // Handle technical info
    Preference.OnPreferenceClickListener listener = new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            updateTechnicalInfo();
            return true;
        }
    };

    // Technical info
    Preference pref_technical_info = screen.findPreference("technical_info");
    Preference pref_technical_network = screen.findPreference("technical_network");
    Preference pref_technical_subscription = screen.findPreference("technical_subscription");
    pref_technical_info.setEnabled(INTENT_VPN_SETTINGS.resolveActivity(this.getPackageManager()) != null);
    pref_technical_info.setIntent(INTENT_VPN_SETTINGS);
    pref_technical_info.setOnPreferenceClickListener(listener);
    pref_technical_network.setOnPreferenceClickListener(listener);
    pref_technical_subscription.setOnPreferenceClickListener(listener);
    updateTechnicalInfo();
}

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

/**
 * Refresh the notification ring tone/*w  w  w.j a  v  a2 s. c o m*/
 */
private void refreshNotificationRingTone() {
    EditTextPreference notificationRingTonePreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATION_RINGTONE_SELECTION_PREFERENCE_KEY);
    notificationRingTonePreference.setSummary(PreferencesManager.getNotificationRingToneName(getActivity()));
}

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

/**
 * Refresh the preferences./*from w ww .  j  a  v  a  2 s .c om*/
 */
private void refreshDisplay() {
    boolean isConnected = Matrix.getInstance(getActivity()).isConnected();
    Context appContext = getActivity().getApplicationContext();

    PreferenceManager preferenceManager = getPreferenceManager();

    // refresh the avatar
    UserAvatarPreference avatarPreference = (UserAvatarPreference) preferenceManager
            .findPreference(PreferencesManager.SETTINGS_PROFILE_PICTURE_PREFERENCE_KEY);
    avatarPreference.refreshAvatar();
    avatarPreference.setEnabled(isConnected);

    // refresh the display name
    final EditTextPreference displaynamePref = (EditTextPreference) preferenceManager
            .findPreference(PreferencesManager.SETTINGS_DISPLAY_NAME_PREFERENCE_KEY);
    displaynamePref.setSummary(mSession.getMyUser().displayname);
    displaynamePref.setText(mSession.getMyUser().displayname);
    displaynamePref.setEnabled(isConnected);

    // change password
    final EditTextPreference changePasswordPref = (EditTextPreference) preferenceManager
            .findPreference(PreferencesManager.SETTINGS_CHANGE_PASSWORD_PREFERENCE_KEY);
    changePasswordPref.setEnabled(isConnected);

    // update the push rules
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(appContext);

    BingRuleSet rules = mSession.getDataHandler().pushRules();

    GcmRegistrationManager gcmMgr = Matrix.getInstance(appContext).getSharedGCMRegistrationManager();

    for (String resourceText : mPushesRuleByResourceId.keySet()) {
        Preference preference = preferenceManager.findPreference(resourceText);

        if (null != preference) {
            if (preference instanceof BingRulePreference) {
                BingRulePreference bingRulePreference = (BingRulePreference) preference;
                bingRulePreference
                        .setEnabled((null != rules) && isConnected && gcmMgr.areDeviceNotificationsAllowed());
                bingRulePreference.setBingRule(mSession.getDataHandler().pushRules()
                        .findDefaultRule(mPushesRuleByResourceId.get(resourceText)));
            } else if (preference instanceof CheckBoxPreference) {
                CheckBoxPreference switchPreference = (CheckBoxPreference) preference;
                if (resourceText.equals(PreferencesManager.SETTINGS_ENABLE_THIS_DEVICE_PREFERENCE_KEY)) {
                    switchPreference.setChecked(gcmMgr.areDeviceNotificationsAllowed());
                } else if (resourceText.equals(PreferencesManager.SETTINGS_TURN_SCREEN_ON_PREFERENCE_KEY)) {
                    switchPreference.setChecked(gcmMgr.isScreenTurnedOn());
                    switchPreference.setEnabled(gcmMgr.areDeviceNotificationsAllowed());
                } else {
                    switchPreference.setEnabled((null != rules) && isConnected);
                    switchPreference.setChecked(preferences.getBoolean(resourceText, false));
                }
            }
        }
    }

    // If notifications are disabled for the current user account or for the current user device
    // The others notifications settings have to be disable too
    boolean areNotifAllowed = rules != null && rules.findDefaultRule(BingRule.RULE_ID_DISABLE_ALL) != null
            && rules.findDefaultRule(BingRule.RULE_ID_DISABLE_ALL).isEnabled;

    Preference notificationSoundPreference = preferenceManager
            .findPreference(PreferencesManager.SETTINGS_NOTIFICATION_RINGTONE_SELECTION_PREFERENCE_KEY);
    notificationSoundPreference.setEnabled(!areNotifAllowed && gcmMgr.areDeviceNotificationsAllowed());

    Preference notificationPrivacyPreference = preferenceManager
            .findPreference(PreferencesManager.SETTINGS_NOTIFICATION_PRIVACY_PREFERENCE_KEY);
    if (notificationPrivacyPreference != null) {
        notificationPrivacyPreference
                .setEnabled(!areNotifAllowed && gcmMgr.areDeviceNotificationsAllowed() && gcmMgr.useGCM());
    }
}

From source file:eu.faircode.netguard.ActivitySettings.java

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    final PreferenceScreen screen = getPreferenceScreen();
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    PreferenceGroup cat_options = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_options"))
            .findPreference("category_options");
    PreferenceGroup cat_advanced = (PreferenceGroup) ((PreferenceGroup) screen
            .findPreference("screen_advanced_options")).findPreference("category_advanced_options");
    PreferenceGroup cat_stats = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_stats"))
            .findPreference("category_stats");
    PreferenceGroup cat_backup = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_backup"))
            .findPreference("category_backup");

    // Handle auto enable
    Preference pref_auto_enable = screen.findPreference("auto_enable");
    pref_auto_enable.setTitle(getString(R.string.setting_auto, prefs.getString("auto_enable", "0")));

    // Handle screen delay
    Preference pref_screen_delay = screen.findPreference("screen_delay");
    pref_screen_delay.setTitle(getString(R.string.setting_delay, prefs.getString("screen_delay", "0")));

    // Handle theme
    Preference pref_screen_theme = screen.findPreference("theme");
    String theme = prefs.getString("theme", "teal");
    String[] themeNames = getResources().getStringArray(R.array.themeNames);
    String[] themeValues = getResources().getStringArray(R.array.themeValues);
    for (int i = 0; i < themeNames.length; i++)
        if (theme.equals(themeValues[i])) {
            pref_screen_theme.setTitle(getString(R.string.setting_theme, themeNames[i]));
            break;
        }//from   w ww.  jav a2 s  . c o  m

    // Wi-Fi home
    MultiSelectListPreference pref_wifi_homes = (MultiSelectListPreference) screen.findPreference("wifi_homes");
    Set<String> ssids = prefs.getStringSet("wifi_homes", new HashSet<String>());
    if (ssids.size() > 0)
        pref_wifi_homes.setTitle(getString(R.string.setting_wifi_home, TextUtils.join(", ", ssids)));
    else
        pref_wifi_homes.setTitle(getString(R.string.setting_wifi_home, "-"));

    WifiManager wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    List<CharSequence> listSSID = new ArrayList<>();
    List<WifiConfiguration> configs = wm.getConfiguredNetworks();
    if (configs != null)
        for (WifiConfiguration config : configs)
            listSSID.add(config.SSID == null ? "NULL" : config.SSID);
    for (String ssid : ssids)
        if (!listSSID.contains(ssid))
            listSSID.add(ssid);
    pref_wifi_homes.setEntries(listSSID.toArray(new CharSequence[0]));
    pref_wifi_homes.setEntryValues(listSSID.toArray(new CharSequence[0]));

    Preference pref_reset_usage = screen.findPreference("reset_usage");
    pref_reset_usage.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Util.areYouSure(ActivitySettings.this, R.string.setting_reset_usage, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    new AsyncTask<Object, Object, Throwable>() {
                        @Override
                        protected Throwable doInBackground(Object... objects) {
                            try {
                                DatabaseHelper.getInstance(ActivitySettings.this).resetUsage(-1);
                                return null;
                            } catch (Throwable ex) {
                                return ex;
                            }
                        }

                        @Override
                        protected void onPostExecute(Throwable ex) {
                            if (ex == null)
                                Toast.makeText(ActivitySettings.this, R.string.msg_completed, Toast.LENGTH_LONG)
                                        .show();
                            else
                                Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
                        }
                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            });
            return false;
        }
    });

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        TwoStatePreference pref_reload_onconnectivity = (TwoStatePreference) screen
                .findPreference("reload_onconnectivity");
        pref_reload_onconnectivity.setChecked(true);
        pref_reload_onconnectivity.setEnabled(false);
    }

    // Handle port forwarding
    Preference pref_forwarding = screen.findPreference("forwarding");
    pref_forwarding.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivity(new Intent(ActivitySettings.this, ActivityForwarding.class));
            return true;
        }
    });

    boolean can = Util.canFilter(this);
    TwoStatePreference pref_log_app = (TwoStatePreference) screen.findPreference("log_app");
    TwoStatePreference pref_filter = (TwoStatePreference) screen.findPreference("filter");
    pref_log_app.setEnabled(can);
    pref_filter.setEnabled(can);
    if (!can) {
        pref_log_app.setSummary(R.string.msg_unavailable);
        pref_filter.setSummary(R.string.msg_unavailable);
    }

    // VPN parameters
    screen.findPreference("vpn4")
            .setTitle(getString(R.string.setting_vpn4, prefs.getString("vpn4", "10.1.10.1")));
    screen.findPreference("vpn6")
            .setTitle(getString(R.string.setting_vpn6, prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1")));
    EditTextPreference pref_dns1 = (EditTextPreference) screen.findPreference("dns");
    EditTextPreference pref_dns2 = (EditTextPreference) screen.findPreference("dns2");
    EditTextPreference pref_ttl = (EditTextPreference) screen.findPreference("ttl");
    List<String> def_dns = Util.getDefaultDNS(this);
    pref_dns1.getEditText().setHint(def_dns.get(0));
    pref_dns2.getEditText().setHint(def_dns.get(1));
    pref_dns1.setTitle(getString(R.string.setting_dns, prefs.getString("dns", def_dns.get(0))));
    pref_dns2.setTitle(getString(R.string.setting_dns, prefs.getString("dns2", def_dns.get(1))));
    pref_ttl.setTitle(getString(R.string.setting_ttl, prefs.getString("ttl", "259200")));

    // SOCKS5 parameters
    screen.findPreference("socks5_addr")
            .setTitle(getString(R.string.setting_socks5_addr, prefs.getString("socks5_addr", "-")));
    screen.findPreference("socks5_port")
            .setTitle(getString(R.string.setting_socks5_port, prefs.getString("socks5_port", "-")));
    screen.findPreference("socks5_username")
            .setTitle(getString(R.string.setting_socks5_username, prefs.getString("socks5_username", "-")));
    screen.findPreference("socks5_password").setTitle(getString(R.string.setting_socks5_password,
            TextUtils.isEmpty(prefs.getString("socks5_username", "")) ? "-" : "*****"));

    // PCAP parameters
    screen.findPreference("pcap_record_size")
            .setTitle(getString(R.string.setting_pcap_record_size, prefs.getString("pcap_record_size", "64")));
    screen.findPreference("pcap_file_size")
            .setTitle(getString(R.string.setting_pcap_file_size, prefs.getString("pcap_file_size", "2")));

    // Watchdog
    screen.findPreference("watchdog")
            .setTitle(getString(R.string.setting_watchdog, prefs.getString("watchdog", "0")));

    // Show resolved
    Preference pref_show_resolved = screen.findPreference("show_resolved");
    if (Util.isPlayStoreInstall(this))
        cat_advanced.removePreference(pref_show_resolved);
    else
        pref_show_resolved.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivity(new Intent(ActivitySettings.this, ActivityDns.class));
                return true;
            }
        });

    // Handle stats
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        cat_stats.removePreference(screen.findPreference("show_top"));
    EditTextPreference pref_stats_frequency = (EditTextPreference) screen.findPreference("stats_frequency");
    EditTextPreference pref_stats_samples = (EditTextPreference) screen.findPreference("stats_samples");
    pref_stats_frequency
            .setTitle(getString(R.string.setting_stats_frequency, prefs.getString("stats_frequency", "1000")));
    pref_stats_samples
            .setTitle(getString(R.string.setting_stats_samples, prefs.getString("stats_samples", "90")));

    // Handle export
    Preference pref_export = screen.findPreference("export");
    pref_export.setEnabled(getIntentCreateExport().resolveActivity(getPackageManager()) != null);
    pref_export.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(getIntentCreateExport(), ActivitySettings.REQUEST_EXPORT);
            return true;
        }
    });

    // Handle import
    Preference pref_import = screen.findPreference("import");
    pref_import.setEnabled(getIntentOpenExport().resolveActivity(getPackageManager()) != null);
    pref_import.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(getIntentOpenExport(), ActivitySettings.REQUEST_IMPORT);
            return true;
        }
    });

    // Hosts file settings
    Preference pref_block_domains = screen.findPreference("use_hosts");
    EditTextPreference pref_rcode = (EditTextPreference) screen.findPreference("rcode");
    Preference pref_hosts_import = screen.findPreference("hosts_import");
    EditTextPreference pref_hosts_url = (EditTextPreference) screen.findPreference("hosts_url");
    final Preference pref_hosts_download = screen.findPreference("hosts_download");

    pref_rcode.setTitle(getString(R.string.setting_rcode, prefs.getString("rcode", "3")));

    if (Util.isPlayStoreInstall(this)) {
        Log.i(TAG, "Play store install");
        cat_options.removePreference(screen.findPreference("update_check"));
        cat_advanced.removePreference(pref_block_domains);
        cat_advanced.removePreference(pref_rcode);
        cat_advanced.removePreference(pref_forwarding);
        cat_backup.removePreference(pref_hosts_import);
        cat_backup.removePreference(pref_hosts_url);
        cat_backup.removePreference(pref_hosts_download);

    } else {
        String last_import = prefs.getString("hosts_last_import", null);
        String last_download = prefs.getString("hosts_last_download", null);
        if (last_import != null)
            pref_hosts_import.setSummary(getString(R.string.msg_import_last, last_import));
        if (last_download != null)
            pref_hosts_download.setSummary(getString(R.string.msg_download_last, last_download));

        // Handle hosts import
        // https://github.com/Free-Software-for-Android/AdAway/wiki/HostsSources
        pref_hosts_import.setEnabled(getIntentOpenHosts().resolveActivity(getPackageManager()) != null);
        pref_hosts_import.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivityForResult(getIntentOpenHosts(), ActivitySettings.REQUEST_HOSTS);
                return true;
            }
        });

        // Handle hosts file download
        pref_hosts_url.setSummary(pref_hosts_url.getText());
        pref_hosts_download.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                final File tmp = new File(getFilesDir(), "hosts.tmp");
                final File hosts = new File(getFilesDir(), "hosts.txt");
                EditTextPreference pref_hosts_url = (EditTextPreference) screen.findPreference("hosts_url");
                try {
                    new DownloadTask(ActivitySettings.this, new URL(pref_hosts_url.getText()), tmp,
                            new DownloadTask.Listener() {
                                @Override
                                public void onCompleted() {
                                    if (hosts.exists())
                                        hosts.delete();
                                    tmp.renameTo(hosts);

                                    String last = SimpleDateFormat.getDateTimeInstance()
                                            .format(new Date().getTime());
                                    prefs.edit().putString("hosts_last_download", last).apply();

                                    if (running) {
                                        pref_hosts_download
                                                .setSummary(getString(R.string.msg_download_last, last));
                                        Toast.makeText(ActivitySettings.this, R.string.msg_downloaded,
                                                Toast.LENGTH_LONG).show();
                                    }

                                    ServiceSinkhole.reload("hosts file download", ActivitySettings.this, false);
                                }

                                @Override
                                public void onCancelled() {
                                    if (tmp.exists())
                                        tmp.delete();
                                }

                                @Override
                                public void onException(Throwable ex) {
                                    if (tmp.exists())
                                        tmp.delete();

                                    if (running)
                                        Toast.makeText(ActivitySettings.this, ex.getMessage(),
                                                Toast.LENGTH_LONG).show();
                                }
                            }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                } catch (MalformedURLException ex) {
                    Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
                }
                return true;
            }
        });
    }

    // Development
    if (!Util.isDebuggable(this))
        screen.removePreference(screen.findPreference("screen_development"));

    // Handle technical info
    Preference.OnPreferenceClickListener listener = new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            updateTechnicalInfo();
            return true;
        }
    };

    // Technical info
    Preference pref_technical_info = screen.findPreference("technical_info");
    Preference pref_technical_network = screen.findPreference("technical_network");
    pref_technical_info.setEnabled(INTENT_VPN_SETTINGS.resolveActivity(this.getPackageManager()) != null);
    pref_technical_info.setIntent(INTENT_VPN_SETTINGS);
    pref_technical_info.setOnPreferenceClickListener(listener);
    pref_technical_network.setOnPreferenceClickListener(listener);
    updateTechnicalInfo();

    markPro(screen.findPreference("theme"), ActivityPro.SKU_THEME);
    markPro(screen.findPreference("install"), ActivityPro.SKU_NOTIFY);
    markPro(screen.findPreference("show_stats"), ActivityPro.SKU_SPEED);
}

From source file:android_network.hetnet.vpn_service.ActivitySettings.java

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    final PreferenceScreen screen = getPreferenceScreen();
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    PreferenceGroup cat_options = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_options"))
            .findPreference("category_options");
    PreferenceGroup cat_advanced = (PreferenceGroup) ((PreferenceGroup) screen
            .findPreference("screen_advanced_options")).findPreference("category_advanced_options");
    PreferenceGroup cat_stats = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_stats"))
            .findPreference("category_stats");
    PreferenceGroup cat_backup = (PreferenceGroup) ((PreferenceGroup) screen.findPreference("screen_backup"))
            .findPreference("category_backup");

    // Handle auto enable
    Preference pref_auto_enable = screen.findPreference("auto_enable");
    pref_auto_enable.setTitle(getString(R.string.setting_auto, prefs.getString("auto_enable", "0")));

    // Handle screen delay
    Preference pref_screen_delay = screen.findPreference("screen_delay");
    pref_screen_delay.setTitle(getString(R.string.setting_delay, prefs.getString("screen_delay", "0")));

    // Handle theme
    Preference pref_screen_theme = screen.findPreference("theme");
    String theme = prefs.getString("theme", "teal");
    String[] themeNames = getResources().getStringArray(R.array.themeNames);
    String[] themeValues = getResources().getStringArray(R.array.themeValues);
    for (int i = 0; i < themeNames.length; i++)
        if (theme.equals(themeValues[i])) {
            pref_screen_theme.setTitle(getString(R.string.setting_theme, themeNames[i]));
            break;
        }/*from w w w. j  a  v a 2 s  .com*/

    // Wi-Fi home
    MultiSelectListPreference pref_wifi_homes = (MultiSelectListPreference) screen.findPreference("wifi_homes");
    Set<String> ssids = prefs.getStringSet("wifi_homes", new HashSet<String>());
    if (ssids.size() > 0)
        pref_wifi_homes.setTitle(getString(R.string.setting_wifi_home, TextUtils.join(", ", ssids)));
    else
        pref_wifi_homes.setTitle(getString(R.string.setting_wifi_home, "-"));

    WifiManager wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    List<CharSequence> listSSID = new ArrayList<>();
    List<WifiConfiguration> configs = wm.getConfiguredNetworks();
    if (configs != null)
        for (WifiConfiguration config : configs)
            listSSID.add(config.SSID == null ? "NULL" : config.SSID);
    for (String ssid : ssids)
        if (!listSSID.contains(ssid))
            listSSID.add(ssid);
    pref_wifi_homes.setEntries(listSSID.toArray(new CharSequence[0]));
    pref_wifi_homes.setEntryValues(listSSID.toArray(new CharSequence[0]));

    Preference pref_reset_usage = screen.findPreference("reset_usage");
    pref_reset_usage.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Util.areYouSure(ActivitySettings.this, R.string.setting_reset_usage, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    new AsyncTask<Object, Object, Throwable>() {
                        @Override
                        protected Throwable doInBackground(Object... objects) {
                            try {
                                DatabaseHelper.getInstance(ActivitySettings.this).resetUsage(-1);
                                return null;
                            } catch (Throwable ex) {
                                return ex;
                            }
                        }

                        @Override
                        protected void onPostExecute(Throwable ex) {
                            if (ex == null)
                                Toast.makeText(ActivitySettings.this, R.string.msg_completed, Toast.LENGTH_LONG)
                                        .show();
                            else
                                Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
                        }
                    }.execute();
                }
            });
            return false;
        }
    });

    // Handle port forwarding
    Preference pref_forwarding = screen.findPreference("forwarding");
    pref_forwarding.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivity(new Intent(ActivitySettings.this, ActivityForwarding.class));
            return true;
        }
    });

    // VPN parameters
    screen.findPreference("vpn4")
            .setTitle(getString(R.string.setting_vpn4, prefs.getString("vpn4", "10.1.10.1")));
    screen.findPreference("vpn6")
            .setTitle(getString(R.string.setting_vpn6, prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1")));
    EditTextPreference pref_dns1 = (EditTextPreference) screen.findPreference("dns");
    EditTextPreference pref_dns2 = (EditTextPreference) screen.findPreference("dns2");
    EditTextPreference pref_ttl = (EditTextPreference) screen.findPreference("ttl");
    List<String> def_dns = Util.getDefaultDNS(this);
    pref_dns1.getEditText().setHint(def_dns.get(0));
    pref_dns2.getEditText().setHint(def_dns.get(1));
    pref_dns1.setTitle(getString(R.string.setting_dns, prefs.getString("dns", def_dns.get(0))));
    pref_dns2.setTitle(getString(R.string.setting_dns, prefs.getString("dns2", def_dns.get(1))));
    pref_ttl.setTitle(getString(R.string.setting_ttl, prefs.getString("ttl", "259200")));

    // SOCKS5 parameters
    screen.findPreference("socks5_addr")
            .setTitle(getString(R.string.setting_socks5_addr, prefs.getString("socks5_addr", "-")));
    screen.findPreference("socks5_port")
            .setTitle(getString(R.string.setting_socks5_port, prefs.getString("socks5_port", "-")));
    screen.findPreference("socks5_username")
            .setTitle(getString(R.string.setting_socks5_username, prefs.getString("socks5_username", "-")));
    screen.findPreference("socks5_password").setTitle(getString(R.string.setting_socks5_password,
            TextUtils.isEmpty(prefs.getString("socks5_username", "")) ? "-" : "*****"));

    // PCAP parameters
    screen.findPreference("pcap_record_size")
            .setTitle(getString(R.string.setting_pcap_record_size, prefs.getString("pcap_record_size", "64")));
    screen.findPreference("pcap_file_size")
            .setTitle(getString(R.string.setting_pcap_file_size, prefs.getString("pcap_file_size", "2")));

    // Watchdog
    screen.findPreference("watchdog")
            .setTitle(getString(R.string.setting_watchdog, prefs.getString("watchdog", "0")));

    // Show resolved
    Preference pref_show_resolved = screen.findPreference("show_resolved");
    if (Util.isPlayStoreInstall(this))
        cat_advanced.removePreference(pref_show_resolved);
    else
        pref_show_resolved.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivity(new Intent(ActivitySettings.this, ActivityDns.class));
                return true;
            }
        });

    // Handle stats
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        cat_stats.removePreference(screen.findPreference("show_top"));
    EditTextPreference pref_stats_frequency = (EditTextPreference) screen.findPreference("stats_frequency");
    EditTextPreference pref_stats_samples = (EditTextPreference) screen.findPreference("stats_samples");
    pref_stats_frequency
            .setTitle(getString(R.string.setting_stats_frequency, prefs.getString("stats_frequency", "1000")));
    pref_stats_samples
            .setTitle(getString(R.string.setting_stats_samples, prefs.getString("stats_samples", "90")));

    // Handle export
    Preference pref_export = screen.findPreference("export");
    pref_export.setEnabled(getIntentCreateExport().resolveActivity(getPackageManager()) != null);
    pref_export.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(getIntentCreateExport(), ActivitySettings.REQUEST_EXPORT);
            return true;
        }
    });

    // Handle import
    Preference pref_import = screen.findPreference("import");
    pref_import.setEnabled(getIntentOpenExport().resolveActivity(getPackageManager()) != null);
    pref_import.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(getIntentOpenExport(), ActivitySettings.REQUEST_IMPORT);
            return true;
        }
    });

    // Hosts file settings
    Preference pref_block_domains = screen.findPreference("use_hosts");
    EditTextPreference pref_rcode = (EditTextPreference) screen.findPreference("rcode");
    Preference pref_hosts_import = screen.findPreference("hosts_import");
    EditTextPreference pref_hosts_url = (EditTextPreference) screen.findPreference("hosts_url");
    final Preference pref_hosts_download = screen.findPreference("hosts_download");

    pref_rcode.setTitle(getString(R.string.setting_rcode, prefs.getString("rcode", "3")));

    if (Util.isPlayStoreInstall(this)) {
        Log.i(TAG, "Play store install");
        cat_options.removePreference(screen.findPreference("update_check"));
        cat_advanced.removePreference(pref_block_domains);
        cat_advanced.removePreference(pref_rcode);
        cat_advanced.removePreference(pref_forwarding);
        cat_backup.removePreference(pref_hosts_import);
        cat_backup.removePreference(pref_hosts_url);
        cat_backup.removePreference(pref_hosts_download);

    } else {
        String last_import = prefs.getString("hosts_last_import", null);
        String last_download = prefs.getString("hosts_last_download", null);
        if (last_import != null)
            pref_hosts_import.setSummary(getString(R.string.msg_import_last, last_import));
        if (last_download != null)
            pref_hosts_download.setSummary(getString(R.string.msg_download_last, last_download));

        // Handle hosts import
        // https://github.com/Free-Software-for-Android/AdAway/wiki/HostsSources
        pref_hosts_import.setEnabled(getIntentOpenHosts().resolveActivity(getPackageManager()) != null);
        pref_hosts_import.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivityForResult(getIntentOpenHosts(), ActivitySettings.REQUEST_HOSTS);
                return true;
            }
        });

        // Handle hosts file download
        pref_hosts_url.setSummary(pref_hosts_url.getText());
        pref_hosts_download.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                final File tmp = new File(getFilesDir(), "hosts.tmp");
                final File hosts = new File(getFilesDir(), "hosts.txt");
                EditTextPreference pref_hosts_url = (EditTextPreference) screen.findPreference("hosts_url");
                try {
                    new DownloadTask(ActivitySettings.this, new URL(pref_hosts_url.getText()), tmp,
                            new DownloadTask.Listener() {
                                @Override
                                public void onCompleted() {
                                    if (hosts.exists())
                                        hosts.delete();
                                    tmp.renameTo(hosts);

                                    String last = SimpleDateFormat.getDateTimeInstance()
                                            .format(new Date().getTime());
                                    prefs.edit().putString("hosts_last_download", last).apply();

                                    if (running) {
                                        pref_hosts_download
                                                .setSummary(getString(R.string.msg_download_last, last));
                                        Toast.makeText(ActivitySettings.this, R.string.msg_downloaded,
                                                Toast.LENGTH_LONG).show();
                                    }

                                    ServiceSinkhole.reload("hosts file download", ActivitySettings.this);
                                }

                                @Override
                                public void onCancelled() {
                                    if (tmp.exists())
                                        tmp.delete();
                                }

                                @Override
                                public void onException(Throwable ex) {
                                    if (tmp.exists())
                                        tmp.delete();

                                    if (running)
                                        Toast.makeText(ActivitySettings.this, ex.getMessage(),
                                                Toast.LENGTH_LONG).show();
                                }
                            }).execute();
                } catch (MalformedURLException ex) {
                    Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
                }
                return true;
            }
        });
    }

    // Development
    if (!Util.isDebuggable(this))
        screen.removePreference(screen.findPreference("screen_development"));

    // Handle technical info
    Preference.OnPreferenceClickListener listener = new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            updateTechnicalInfo();
            return true;
        }
    };

    // Technical info
    Preference pref_technical_info = screen.findPreference("technical_info");
    Preference pref_technical_network = screen.findPreference("technical_network");
    Preference pref_technical_subscription = screen.findPreference("technical_subscription");
    pref_technical_info.setEnabled(INTENT_VPN_SETTINGS.resolveActivity(this.getPackageManager()) != null);
    pref_technical_info.setIntent(INTENT_VPN_SETTINGS);
    pref_technical_info.setOnPreferenceClickListener(listener);
    pref_technical_network.setOnPreferenceClickListener(listener);
    pref_technical_subscription.setOnPreferenceClickListener(listener);
    updateTechnicalInfo();

    //        markPro(screen.findPreference("theme"), ActivityPro.SKU_THEME);
    //        markPro(screen.findPreference("install"), ActivityPro.SKU_NOTIFY);
    //        markPro(screen.findPreference("show_stats"), ActivityPro.SKU_SPEED);
}

From source file:eu.faircode.adblocker.ActivitySettings.java

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    final PreferenceScreen screen = getPreferenceScreen();
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    PreferenceCategory cat_options = (PreferenceCategory) screen.findPreference("category_options");
    PreferenceCategory cat_advanced = (PreferenceCategory) screen.findPreference("category_advanced_options");
    PreferenceCategory cat_backup = (PreferenceCategory) screen.findPreference("category_backup");
    PreferenceCategory cat_development = (PreferenceCategory) screen.findPreference("category_development");

    // Handle auto enable
    Preference pref_auto_enable = screen.findPreference("auto_enable");
    pref_auto_enable.setTitle(getString(R.string.setting_auto, prefs.getString("auto_enable", "0")));

    // Handle screen delay
    Preference pref_screen_delay = screen.findPreference("screen_delay");
    pref_screen_delay.setTitle(getString(R.string.setting_delay, prefs.getString("screen_delay", "0")));

    // Handle theme
    Preference pref_screen_theme = screen.findPreference("theme");
    String theme = prefs.getString("theme", "teal");
    String[] themeNames = getResources().getStringArray(R.array.themeNames);
    String[] themeValues = getResources().getStringArray(R.array.themeValues);
    for (int i = 0; i < themeNames.length; i++)
        if (theme.equals(themeValues[i])) {
            pref_screen_theme.setTitle(getString(R.string.setting_theme, themeNames[i]));
            break;
        }// www .  j  a v a 2 s.  c  om

    // Wi-Fi home
    MultiSelectListPreference pref_wifi_homes = (MultiSelectListPreference) screen.findPreference("wifi_homes");
    Set<String> ssid = prefs.getStringSet("wifi_homes", new HashSet<String>());
    if (ssid.size() > 0)
        pref_wifi_homes.setTitle(getString(R.string.setting_wifi_home, TextUtils.join(", ", ssid)));
    else
        pref_wifi_homes.setTitle(getString(R.string.setting_wifi_home, "-"));

    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    List<CharSequence> listSSID = new ArrayList<>();
    List<WifiConfiguration> configs = wm.getConfiguredNetworks();
    if (configs != null)
        for (WifiConfiguration config : configs)
            listSSID.add(config.SSID == null ? "NULL" : config.SSID);
    pref_wifi_homes.setEntries(listSSID.toArray(new CharSequence[0]));
    pref_wifi_homes.setEntryValues(listSSID.toArray(new CharSequence[0]));

    // Filtering always enabled
    //        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
    //            cat_advanced.removePreference(screen.findPreference("filter"));

    Preference pref_reset_usage = screen.findPreference("reset_usage");
    pref_reset_usage.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Util.areYouSure(ActivitySettings.this, R.string.setting_reset_usage, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    new AsyncTask<Object, Object, Throwable>() {
                        @Override
                        protected Throwable doInBackground(Object... objects) {
                            try {
                                DatabaseHelper.getInstance(ActivitySettings.this).resetUsage(-1);
                                return null;
                            } catch (Throwable ex) {
                                return ex;
                            }
                        }

                        @Override
                        protected void onPostExecute(Throwable ex) {
                            if (ex == null)
                                Toast.makeText(ActivitySettings.this, R.string.msg_completed, Toast.LENGTH_LONG)
                                        .show();
                            else
                                Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
                        }
                    }.execute();
                }
            });
            return false;
        }
    });

    // Handle port forwarding
    Preference pref_forwarding = screen.findPreference("forwarding");
    pref_forwarding.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivity(new Intent(ActivitySettings.this, ActivityForwarding.class));
            return true;
        }
    });

    // VPN parameters
    screen.findPreference("vpn4")
            .setTitle(getString(R.string.setting_vpn4, prefs.getString("vpn4", "10.1.10.1")));
    screen.findPreference("vpn6")
            .setTitle(getString(R.string.setting_vpn6, prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1")));
    EditTextPreference pref_dns = (EditTextPreference) screen.findPreference("dns");
    List<String> def_dns = Util.getDefaultDNS(this);
    pref_dns.getEditText().setHint(def_dns.get(0));
    pref_dns.setTitle(getString(R.string.setting_dns, prefs.getString("dns", def_dns.get(0))));

    // PCAP parameters
    screen.findPreference("pcap_record_size")
            .setTitle(getString(R.string.setting_pcap_record_size, prefs.getString("pcap_record_size", "64")));
    screen.findPreference("pcap_file_size")
            .setTitle(getString(R.string.setting_pcap_file_size, prefs.getString("pcap_file_size", "2")));

    // Handle stats
    EditTextPreference pref_stats_frequency = (EditTextPreference) screen.findPreference("stats_frequency");
    EditTextPreference pref_stats_samples = (EditTextPreference) screen.findPreference("stats_samples");
    pref_stats_frequency
            .setTitle(getString(R.string.setting_stats_frequency, prefs.getString("stats_frequency", "1000")));
    pref_stats_samples
            .setTitle(getString(R.string.setting_stats_samples, prefs.getString("stats_samples", "90")));

    // Handle export
    Preference pref_export = screen.findPreference("export");
    pref_export.setEnabled(getIntentCreateExport().resolveActivity(getPackageManager()) != null);
    pref_export.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(getIntentCreateExport(), ActivitySettings.REQUEST_EXPORT);
            return true;
        }
    });

    // Handle import
    Preference pref_import = screen.findPreference("import");
    pref_import.setEnabled(getIntentOpenExport().resolveActivity(getPackageManager()) != null);
    pref_import.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(getIntentOpenExport(), ActivitySettings.REQUEST_IMPORT);
            return true;
        }
    });

    // Hosts file settings
    Preference pref_block_domains = screen.findPreference("use_hosts");
    Preference pref_hosts_import = screen.findPreference("hosts_import");
    EditTextPreference pref_hosts_url = (EditTextPreference) screen.findPreference("hosts_url");
    final Preference pref_hosts_download = screen.findPreference("hosts_download");

    if (Util.isPlayStoreInstall(this)) {
        cat_options.removePreference(screen.findPreference("update_check"));
        cat_advanced.removePreference(pref_block_domains);
        cat_advanced.removePreference(pref_forwarding);
        cat_backup.removePreference(pref_hosts_import);
        cat_backup.removePreference(pref_hosts_url);
        cat_backup.removePreference(pref_hosts_download);

    } else {
        try {

            AssetManager am = getAssets();

            InputStream inputStream = getResources().openRawResource(R.raw.hosts);
            File hfile = createFileFromInputStream(inputStream);

            pref_block_domains.setEnabled(hfile.exists());
        } catch (Exception e) {
            e.printStackTrace();
        }

        String last_import = prefs.getString("hosts_last_import", null);
        String last_download = prefs.getString("hosts_last_download", null);
        if (last_import != null)
            pref_hosts_import.setSummary(getString(R.string.msg_import_last, last_import));
        if (last_download != null)
            pref_hosts_download.setSummary(getString(R.string.msg_download_last, last_download));

        // Handle hosts import
        // https://github.com/Free-Software-for-Android/AdAway/wiki/HostsSources
        pref_hosts_import.setEnabled(getIntentOpenHosts().resolveActivity(getPackageManager()) != null);
        pref_hosts_import.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivityForResult(getIntentOpenHosts(), ActivitySettings.REQUEST_HOSTS);
                return true;
            }
        });

        // Handle hosts file download
        pref_hosts_url.setSummary(pref_hosts_url.getText());
        pref_hosts_download.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                final File tmp = new File(getFilesDir(), "hosts.tmp");
                final File hosts = new File(getFilesDir(), "host/hosts.txt");
                EditTextPreference pref_hosts_url = (EditTextPreference) screen.findPreference("hosts_url");
                try {
                    new DownloadTask(ActivitySettings.this, new URL(pref_hosts_url.getText()), tmp,
                            new DownloadTask.Listener() {
                                @Override
                                public void onCompleted() {
                                    if (hosts.exists())
                                        hosts.delete();
                                    tmp.renameTo(hosts);

                                    String last = SimpleDateFormat.getDateTimeInstance()
                                            .format(new Date().getTime());
                                    prefs.edit().putString("hosts_last_download", last).apply();

                                    if (running) {
                                        getPreferenceScreen().findPreference("use_hosts").setEnabled(true);
                                        pref_hosts_download
                                                .setSummary(getString(R.string.msg_download_last, last));
                                        Toast.makeText(ActivitySettings.this, R.string.msg_downloaded,
                                                Toast.LENGTH_LONG).show();
                                    }

                                    ServiceSinkhole.reload("hosts file download", ActivitySettings.this);
                                }

                                @Override
                                public void onCancelled() {
                                    if (tmp.exists())
                                        tmp.delete();
                                }

                                @Override
                                public void onException(Throwable ex) {
                                    if (tmp.exists())
                                        tmp.delete();

                                    if (running)
                                        Toast.makeText(ActivitySettings.this, ex.getMessage(),
                                                Toast.LENGTH_LONG).show();
                                }
                            }).execute();
                } catch (MalformedURLException ex) {
                    Toast.makeText(ActivitySettings.this, ex.toString(), Toast.LENGTH_LONG).show();
                }
                return true;
            }
        });
    }

    // Development
    Preference pref_show_resolved = screen.findPreference("show_resolved");
    if (!(Util.isDebuggable(this) || Util.getSelfVersionName(this).contains("beta"))) {
        screen.removePreference(cat_development);
        prefs.edit().remove("loglevel").apply();
    } else if (!Util.isDebuggable(this))
        cat_development.removePreference(pref_show_resolved);

    // Show resolved
    pref_show_resolved.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            startActivity(new Intent(ActivitySettings.this, ActivityDns.class));
            return true;
        }
    });

    // Handle technical info
    Preference.OnPreferenceClickListener listener = new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            updateTechnicalInfo();
            return true;
        }
    };

    // Technical info
    Preference pref_technical_info = screen.findPreference("technical_info");
    Preference pref_technical_network = screen.findPreference("technical_network");
    Preference pref_technical_subscription = screen.findPreference("technical_subscription");
    pref_technical_info.setEnabled(INTENT_VPN_SETTINGS.resolveActivity(this.getPackageManager()) != null);
    pref_technical_info.setIntent(INTENT_VPN_SETTINGS);
    pref_technical_info.setOnPreferenceClickListener(listener);
    pref_technical_network.setOnPreferenceClickListener(listener);
    pref_technical_subscription.setOnPreferenceClickListener(listener);
    updateTechnicalInfo();
}

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

/**
 * Refresh the notification privacy setting
 */// w  w w  .ja va  2  s.  c  o m
private void refreshNotificationPrivacy() {
    EditTextPreference notificationPrivacyPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATION_PRIVACY_PREFERENCE_KEY);

    if (notificationPrivacyPreference != null) {
        GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(getActivity())
                .getSharedGCMRegistrationManager();

        // this setting apply only with GCM for the moment
        if (gcmRegistrationManager.useGCM()) {
            String notificationPrivacyString = NotificationPrivacyActivity.getNotificationPrivacyString(
                    getActivity().getApplicationContext(), gcmRegistrationManager.getNotificationPrivacy());
            notificationPrivacyPreference.setSummary(notificationPrivacyString);
        } else {
            PreferenceCategory notificationsSettingsCategory = (PreferenceCategory) findPreference(
                    PreferencesManager.SETTINGS_NOTIFICATIONS_KEY);
            notificationsSettingsCategory.removePreference(notificationPrivacyPreference);
        }
    }
}

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();/*from w  w w .  j a va2  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();
}