Example usage for android.net.wifi WifiManager getConfiguredNetworks

List of usage examples for android.net.wifi WifiManager getConfiguredNetworks

Introduction

In this page you can find the example usage for android.net.wifi WifiManager getConfiguredNetworks.

Prototype

public List<WifiConfiguration> getConfiguredNetworks() 

Source Link

Document

Return a list of all the networks configured for the current foreground user.

Usage

From source file:de.ub0r.android.wifibarcode.WifiBarcodeActivity.java

/**
 * Load wifi configurations.//from   w  w w .ja v a  2  s .com
 */
private void loadWifiConfigurations() {
    WifiAdapter adapter = (WifiAdapter) mSpConfigs.getAdapter();
    WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
    List<WifiConfiguration> wcs = wm.getConfiguredNetworks();
    String currentSSID = wm.getConnectionInfo().getSSID();
    Log.d(TAG, "currentSSID=", currentSSID);
    WifiConfiguration custom = new WifiConfiguration();
    custom.SSID = getString(R.string.custom);
    adapter.clear();
    adapter.add(custom);
    flushWifiPasswords();
    Log.d(TAG, "#wcs=", wcs == null ? "null" : wcs.size());
    if (wcs != null) {
        int selected = -1;
        for (WifiConfiguration wc : wcs) {
            adapter.add(wc, getWifiPassword(wc));
            Log.d(TAG, "wc.SSID=", wc.SSID);
            if (mFirstLoad && currentSSID != null && currentSSID.equals(wc.SSID)) {
                selected = adapter.getCount() - 1;
                Log.d(TAG, "selected=", selected);
            }
        }
        if (selected > 0) {
            // mFirstLoad == true
            mSpConfigs.setSelection(selected);
        }
        mFirstLoad = false;
    }
}

From source file:com.landenlabs.all_devtool.NetFragment.java

private void clean_networks() {
    StringBuilder sb = new StringBuilder();
    final WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);
    if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {
        try {/*from   ww  w .  ja  va2s .c o m*/
            List<WifiConfiguration> listWifiCfg = wifiMgr.getConfiguredNetworks();
            for (WifiConfiguration wifiCfg : listWifiCfg) {

                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) {

                    // Remove network connections with no Password.
                    if (wifiMgr.removeNetwork(wifiCfg.networkId)) {
                        sb.append(wifiCfg.SSID);
                        sb.append("\n");
                    }
                }
            }
        } catch (Exception ex) {

        }
    }

    if (sb.length() != 0) {
        Toast.makeText(this.getContext(), "Removed Networks: " + sb.toString(), Toast.LENGTH_LONG).show();
    }
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Connect to a given Wifi network with a given 'wpa', 'wep', 'open' type and a password", example = "")
@APIParam(params = { "ssidName", "type", "password" })
public void connectWifi(String networkSSID, String type, String networkPass) {

    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String
    // should contain ssid in quotes

    if (type.equals("wep")) {
        // wep//  ww w  . j av  a 2 s.  c  o  m
        conf.wepKeys[0] = "\"" + networkPass + "\"";
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    } else if (type.equals("wpa")) {
        // wpa
        conf.preSharedKey = "\"" + networkPass + "\"";
    } else if (type.equals("open")) {
        // open
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    }

    WifiManager wifiManager = (WifiManager) a.get().getSystemService(Context.WIFI_SERVICE);
    wifiManager.addNetwork(conf);

    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    for (WifiConfiguration i : list) {
        if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
            wifiManager.disconnect();
            wifiManager.enableNetwork(i.networkId, true);
            wifiManager.reconnect();

            break;
        }
    }

}

From source file:org.restcomm.app.qoslib.Utils.QosInfo.java

private WifiConfiguration getWifiConfig() {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    WifiConfiguration activeConfig = null;
    if (wifiManager.getConfiguredNetworks() == null)
        return null;

    for (WifiConfiguration conn : wifiManager.getConfiguredNetworks()) {
        if ((conn.BSSID != null && conn.BSSID.equals(wifiInfo.getBSSID()))
                || (conn.SSID != null && conn.SSID.equals(wifiInfo.getSSID()))) {
            activeConfig = conn;//from  ww w .j a  v a  2  s.  c om
            break;
        }
    }
    if (activeConfig != null) {
        return activeConfig;
    }
    return null;
}

From source file:org.restcomm.app.qoslib.Services.Events.EventManager.java

public WifiConfiguration getWifiConfig() {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    WifiConfiguration activeConfig = null;
    if (wifiManager.getConfiguredNetworks() == null)
        return null;

    for (WifiConfiguration conn : wifiManager.getConfiguredNetworks()) {
        if ((conn.BSSID != null && conn.BSSID.equals(wifiInfo.getBSSID()))
                || (conn.SSID != null && conn.SSID.equals(wifiInfo.getSSID()))) {
            activeConfig = conn;//w  w w  .  ja  v  a2s. c o  m
            break;
        }
    }
    if (activeConfig != null) {
        return activeConfig;
    }
    return null;
}

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  w w  .  j a va 2 s  .  com*/

    // 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: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;
        }//from   ww  w . j a v  a  2 s. c o  m

    // 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: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 w w . j a  va2s. 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  ww.  ja v  a2s .  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();
                        }
                    }.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:org.sipdroid.sipua.ui.Receiver.java

@Override
public void onReceive(Context context, Intent intent) {
    String intentAction = intent.getAction();
    if (!Sipdroid.on(context))
        return;/*from www .  ja v  a2  s . com*/
    if (!Sipdroid.release)
        Log.i("SipUA:", intentAction);
    if (mContext == null)
        mContext = context;
    if (intentAction.equals(Intent.ACTION_BOOT_COMPLETED)) {
        on_vpn(false);
        engine(context).register();
    } else if (intentAction.equals(ConnectivityManager.CONNECTIVITY_ACTION)
            || intentAction.equals(ACTION_EXTERNAL_APPLICATIONS_AVAILABLE)
            || intentAction.equals(ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)
            || intentAction.equals(Intent.ACTION_PACKAGE_REPLACED)) {
        engine(context).register();
    } else if (intentAction.equals(ACTION_VPN_CONNECTIVITY) && intent.hasExtra("connection_state")) {
        String state = intent.getSerializableExtra("connection_state").toString();
        if (state != null && on_vpn() != state.equals("CONNECTED")) {
            on_vpn(state.equals("CONNECTED"));
            for (SipProvider sip_provider : engine(context).sip_providers)
                if (sip_provider != null)
                    sip_provider.haltConnections();
            engine(context).register();
        }
    } else if (intentAction.equals(ACTION_DATA_STATE_CHANGED)) {
        engine(context).registerMore();
    } else if (intentAction.equals(ACTION_PHONE_STATE_CHANGED)
            && !intent.getBooleanExtra(context.getString(R.string.app_name), false)) {
        stopRingtone();
        pstn_state = intent.getStringExtra("state");
        pstn_time = SystemClock.elapsedRealtime();
        if (pstn_state.equals("IDLE") && call_state != UserAgent.UA_STATE_IDLE)
            broadcastCallStateChanged(null, null);
        if (!pstn_state.equals("IDLE") && call_state == UserAgent.UA_STATE_INCALL)
            mHandler.sendEmptyMessageDelayed(MSG_HOLD, 5000);
        else if (!pstn_state.equals("IDLE") && (call_state == UserAgent.UA_STATE_INCOMING_CALL
                || call_state == UserAgent.UA_STATE_OUTGOING_CALL))
            mHandler.sendEmptyMessageDelayed(MSG_HANGUP, 5000);
        else if (pstn_state.equals("IDLE")) {
            mHandler.removeMessages(MSG_HOLD);
            mHandler.removeMessages(MSG_HANGUP);
            if (call_state == UserAgent.UA_STATE_HOLD)
                mHandler.sendEmptyMessageDelayed(MSG_HOLD, 1000);
        }
    } else if (intentAction.equals(ACTION_DOCK_EVENT)) {
        docked = intent.getIntExtra(EXTRA_DOCK_STATE, -1) & 7;
        if (call_state == UserAgent.UA_STATE_INCALL)
            engine(mContext).speaker(speakermode());
    } else if (intentAction.equals(ACTION_SCO_AUDIO_STATE_CHANGED)) {
        bluetooth = intent.getIntExtra(EXTRA_SCO_AUDIO_STATE, -1);
        progress();
        RtpStreamSender.changed = true;
    } else if (intentAction.equals(Intent.ACTION_HEADSET_PLUG)) {
        headset = intent.getIntExtra("state", -1);
        if (call_state == UserAgent.UA_STATE_INCALL)
            engine(mContext).speaker(speakermode());
    } else if (intentAction.equals(Intent.ACTION_SCREEN_ON)) {
        if (!PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                org.sipdroid.sipua.ui.Settings.PREF_OWNWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_OWNWIFI))
            alarm(0, OwnWifi.class);
    } else if (intentAction.equals(Intent.ACTION_USER_PRESENT)) {
        mHandler.sendEmptyMessageDelayed(MSG_ENABLE, 3000);
    } else if (intentAction.equals(Intent.ACTION_SCREEN_OFF)) {
        if (PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                org.sipdroid.sipua.ui.Settings.PREF_OWNWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_OWNWIFI)) {
            WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wi = wm.getConnectionInfo();
            if (wm.getWifiState() != WifiManager.WIFI_STATE_ENABLED || wi == null
                    || wi.getSupplicantState() != SupplicantState.COMPLETED || wi.getIpAddress() == 0)
                alarm(2 * 60, OwnWifi.class);
            else
                alarm(15 * 60, OwnWifi.class);
        }
        if (SipdroidEngine.pwl != null)
            for (PowerManager.WakeLock pwl : SipdroidEngine.pwl)
                if (pwl != null && pwl.isHeld()) {
                    pwl.release();
                    pwl.acquire();
                }
    } else if (intentAction.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
        if (PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                org.sipdroid.sipua.ui.Settings.PREF_SELECTWIFI,
                org.sipdroid.sipua.ui.Settings.DEFAULT_SELECTWIFI))
            mHandler.sendEmptyMessageDelayed(MSG_SCAN, 3000);
    } else if (intentAction.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
        if (SystemClock.uptimeMillis() > lastscan + 45000
                && PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                        org.sipdroid.sipua.ui.Settings.PREF_SELECTWIFI,
                        org.sipdroid.sipua.ui.Settings.DEFAULT_SELECTWIFI)) {
            WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wi = wm.getConnectionInfo();
            String activeSSID = null;
            if (wi != null)
                activeSSID = wi.getSSID();
            if (activeSSID != null && (activeSSID.length() == 0 || activeSSID.equals("0x")))
                activeSSID = null;
            List<ScanResult> mScanResults = wm.getScanResults();
            List<WifiConfiguration> configurations = wm.getConfiguredNetworks();
            if (configurations != null) {
                WifiConfiguration bestconfig = null, maxconfig = null, activeconfig = null;
                for (final WifiConfiguration config : configurations) {
                    if (maxconfig == null || config.priority > maxconfig.priority) {
                        maxconfig = config;
                    }
                    if (config.SSID != null
                            && (config.SSID.equals("\"" + activeSSID + "\"") || config.SSID.equals(activeSSID)))
                        activeconfig = config;
                }
                ScanResult bestscan = null, activescan = null;
                if (mScanResults != null)
                    for (final ScanResult scan : mScanResults) {
                        for (final WifiConfiguration config : configurations) {
                            if (config.SSID != null && config.SSID.equals("\"" + scan.SSID + "\"")) {
                                if (bestscan == null || scan.level > bestscan.level) {
                                    bestscan = scan;
                                    bestconfig = config;
                                }
                                if (config == activeconfig)
                                    activescan = scan;
                            }
                        }
                    }
                if (activescan != null)
                    System.out.println("debug wifi asu(active)" + asu(activescan));
                if (bestconfig != null && (activeconfig == null || bestconfig.priority != activeconfig.priority)
                        && asu(bestscan) > asu(activescan) * 1.5 &&
                        /* (activeSSID == null || activescan != null) && */ asu(bestscan) > 22) {
                    if (!Sipdroid.release)
                        Log.i("SipUA:", "changing to " + bestconfig.SSID);
                    if (activeSSID == null || !activeSSID.equals(bestscan.SSID))
                        wm.disconnect();
                    bestconfig.priority = maxconfig.priority + 1;
                    wm.updateNetwork(bestconfig);
                    wm.enableNetwork(bestconfig.networkId, true);
                    wm.saveConfiguration();
                    if (activeSSID == null || !activeSSID.equals(bestscan.SSID))
                        wm.reconnect();
                    lastscan = SystemClock.uptimeMillis();
                } else if (activescan != null && asu(activescan) < 15) {
                    wm.disconnect();
                    wm.disableNetwork(activeconfig.networkId);
                    wm.saveConfiguration();
                }
            }
        }
    }
}