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:Main.java

public static List<WifiConfiguration> getWifiConfigrations(Context context) {
    WifiManager mainWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    List<WifiConfiguration> list = mainWifi.getConfiguredNetworks();
    return list;//www .  j  av a  2s  .co  m
}

From source file:Main.java

public static List<WifiConfiguration> getHotspotsList(Context context) {
    final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if (wifiManager == null)
        return new ArrayList<WifiConfiguration>();
    return wifiManager.getConfiguredNetworks();
}

From source file:com.conferenceengineer.android.iosched.util.WiFiUtils.java

public static boolean isWiFiApConfigured(final Context context) {
    final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    final List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();

    if (configs == null)
        return false;

    // Check for existing APs.
    final String conferenceSSID = String.format("\"%s\"", Config.WIFI_SSID);
    for (WifiConfiguration config : configs) {
        if (conferenceSSID.equalsIgnoreCase(config.SSID))
            return true;
    }//from  ww  w.ja v a 2  s. com
    return false;
}

From source file:com.conferenceengineer.android.iosched.util.WiFiUtils.java

/**
 * Helper method to decide whether to bypass conference WiFi setup.  Return true if
 * WiFi AP is already configured (WiFi adapter enabled) or WiFi configuration is complete
 * as per shared preference.//from   w w  w  .jav a2s.c  om
 */
public static boolean shouldBypassWiFiSetup(final Context context) {
    final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

    // Is WiFi on?
    if (wifiManager.isWifiEnabled()) {
        // Check for existing APs.
        final List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        final String conferenceSSID = String.format("\"%s\"", Config.WIFI_SSID);
        for (WifiConfiguration config : configs) {
            if (conferenceSSID.equalsIgnoreCase(config.SSID))
                return true;
        }
    }

    return WIFI_CONFIG_DONE.equals(getWiFiConfigStatus(context));
}

From source file:org.wahtod.wififixer.ui.KnownNetworksFragment.java

public static List<String> getNetworks(Context context) {
    WifiManager wm = AsyncWifiManager.getWifiManager(context);
    List<WifiConfiguration> wifiConfigs = wm.getConfiguredNetworks();
    if (wifiConfigs == null || wifiConfigs.isEmpty())
        return new ArrayList<>();

    List<String> networks = new ArrayList<String>();
    for (WifiConfiguration wfResult : wifiConfigs) {
        /*//from  w  ww . j  a  va  2  s . co  m
         * Make sure there's a 1:1 correlation between
        * getConfiguredNetworks() and the array
        */
        if (wfResult.SSID != null && wfResult.SSID.length() > 0)
            networks.add(StringUtil.removeQuotes(wfResult.SSID));
        else
            networks.add(context.getString(R.string.null_ssid));
    }
    return networks;
}

From source file:ru.glesik.wifireminders.AddReminderActivity.java

protected void onResume() {
    super.onResume();
    // Creating adapter to populate spinnerSSID items.
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    Spinner Items = (Spinner) findViewById(R.id.spinnerSSID);
    Items.setAdapter(adapter);//from   w  ww  .  ja v  a2 s . c o m
    WifiManager mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    // Start scanning for visible networks.
    if (mainWifi.isWifiEnabled()) {
        mainWifi.startScan();
        // Getting list of stored networks.
        List<WifiConfiguration> wifiList = mainWifi.getConfiguredNetworks();
        for (WifiConfiguration result : wifiList) {
            // Removing quotes.
            adapter.add(result.SSID.toString().replaceAll("^\"|\"$", ""));
        }
        adapter.notifyDataSetChanged();
    } else {
        new AlertDialog.Builder(this).setTitle(R.string.error_wifi_off_title)
                .setMessage(R.string.error_wifi_off_text)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
                        finish();
                    }
                }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setIcon(android.R.drawable.ic_dialog_alert).show();
    }
}

From source file:riddimon.android.asianetautologin.CredentialActivity.java

private void refreshNetworkSpinnerIfNecessary() {
    if (mSsids != null && mSsids.size() != 0)
        return;/*  w w w.  j a v a 2 s.c  o m*/
    //get wifi networks
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    List<WifiConfiguration> lwc = wm.getConfiguredNetworks();
    WifiInfo wi = wm.getConnectionInfo();
    String wssid = null;
    if (wi != null && wm.isWifiEnabled()) {
        String ssid = wi.getSSID();
        if (!TextUtils.isEmpty(ssid)) {
            wssid = ssid.replace("\"", "");
        }
    }

    mSsids = new ArrayList<String>();
    int selection = 0;
    if (lwc != null) {
        int i = -1;
        for (WifiConfiguration wc : lwc) {
            i++;
            String ssid = TextUtils.isEmpty(wc.SSID) ? "" : wc.SSID.replace("\"", "");
            mSsids.add(ssid);
            if (!TextUtils.isEmpty(wssid) && ssid.equals(wssid)) {
                selection = i;
            }
        }
    }

    mSsid.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mSsids));
    if (mSsids != null && mSsids.size() > 0) {
        mSsid.setSelection(selection);
    }
}

From source file:be.ppareit.swiftp.gui.PreferenceFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    Resources resources = getResources();

    TwoStatePreference runningPref = findPref("running_switch");
    updateRunningState();//ww w . j  av a2  s .  c  om
    runningPref.setOnPreferenceChangeListener((preference, newValue) -> {
        if ((Boolean) newValue) {
            startServer();
        } else {
            stopServer();
        }
        return true;
    });

    PreferenceScreen prefScreen = findPref("preference_screen");
    Preference marketVersionPref = findPref("market_version");
    marketVersionPref.setOnPreferenceClickListener(preference -> {
        // start the market at our application
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("market://details?id=be.ppareit.swiftp"));
        try {
            // this can fail if there is no market installed
            startActivity(intent);
        } catch (Exception e) {
            Cat.e("Failed to launch the market.");
            e.printStackTrace();
        }
        return false;
    });
    if (!App.isFreeVersion()) {
        prefScreen.removePreference(marketVersionPref);
    }

    updateLoginInfo();

    EditTextPreference usernamePref = findPref("username");
    usernamePref.setOnPreferenceChangeListener((preference, newValue) -> {
        String newUsername = (String) newValue;
        if (preference.getSummary().equals(newUsername))
            return false;
        if (!newUsername.matches("[a-zA-Z0-9]+")) {
            Toast.makeText(getActivity(), R.string.username_validation_error, Toast.LENGTH_LONG).show();
            return false;
        }
        stopServer();
        return true;
    });

    mPassWordPref = findPref("password");
    mPassWordPref.setOnPreferenceChangeListener((preference, newValue) -> {
        stopServer();
        return true;
    });
    mAutoconnectListPref = findPref("autoconnect_preference");
    mAutoconnectListPref.setOnPopulateListener(pref -> {
        Cat.d("autoconnect populate listener");

        WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        if (configs == null) {
            Cat.e("Unable to receive wifi configurations, bark at user and bail");
            Toast.makeText(getActivity(), R.string.autoconnect_error_enable_wifi_for_access_points,
                    Toast.LENGTH_LONG).show();
            return;
        }
        CharSequence[] ssids = new CharSequence[configs.size()];
        CharSequence[] niceSsids = new CharSequence[configs.size()];
        for (int i = 0; i < configs.size(); ++i) {
            ssids[i] = configs.get(i).SSID;
            String ssid = configs.get(i).SSID;
            if (ssid.length() > 2 && ssid.startsWith("\"") && ssid.endsWith("\"")) {
                ssid = ssid.substring(1, ssid.length() - 1);
            }
            niceSsids[i] = ssid;
        }
        pref.setEntries(niceSsids);
        pref.setEntryValues(ssids);
    });
    mAutoconnectListPref.setOnPreferenceClickListener(preference -> {
        Cat.d("Clicked");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    new AlertDialog.Builder(getContext()).setTitle(R.string.request_coarse_location_dlg_title)
                            .setMessage(R.string.request_coarse_location_dlg_message)
                            .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                                requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                                        ACCESS_COARSE_LOCATION_REQUEST_CODE);
                            }).setOnCancelListener(dialog -> {
                                mAutoconnectListPref.getDialog().cancel();
                            }).create().show();
                } else {
                    requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                            ACCESS_COARSE_LOCATION_REQUEST_CODE);
                }
            }
        }
        return false;
    });

    EditTextPreference portnum_pref = findPref("portNum");
    portnum_pref.setSummary(sp.getString("portNum", resources.getString(R.string.portnumber_default)));
    portnum_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        String newPortnumString = (String) newValue;
        if (preference.getSummary().equals(newPortnumString))
            return false;
        int portnum = 0;
        try {
            portnum = Integer.parseInt(newPortnumString);
        } catch (Exception e) {
            Cat.d("Error parsing port number! Moving on...");
        }
        if (portnum <= 0 || 65535 < portnum) {
            Toast.makeText(getActivity(), R.string.port_validation_error, Toast.LENGTH_LONG).show();
            return false;
        }
        preference.setSummary(newPortnumString);
        stopServer();
        return true;
    });

    Preference chroot_pref = findPref("chrootDir");
    chroot_pref.setSummary(FsSettings.getChrootDirAsString());
    chroot_pref.setOnPreferenceClickListener(preference -> {
        AlertDialog folderPicker = new FolderPickerDialogBuilder(getActivity(), FsSettings.getChrootDir())
                .setSelectedButton(R.string.select, path -> {
                    if (preference.getSummary().equals(path))
                        return;
                    if (!FsSettings.setChrootDir(path))
                        return;
                    // TODO: this is a hotfix, create correct resources, improve UI/UX
                    final File root = new File(path);
                    if (!root.canRead()) {
                        Toast.makeText(getActivity(), "Notice that we can't read/write in this folder.",
                                Toast.LENGTH_LONG).show();
                    } else if (!root.canWrite()) {
                        Toast.makeText(getActivity(),
                                "Notice that we can't write in this folder, reading will work. Writing in sub folders might work.",
                                Toast.LENGTH_LONG).show();
                    }

                    preference.setSummary(path);
                    stopServer();
                }).setNegativeButton(R.string.cancel, null).create();
        folderPicker.show();
        return true;
    });

    final CheckBoxPreference wakelock_pref = findPref("stayAwake");
    wakelock_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        stopServer();
        return true;
    });

    final CheckBoxPreference writeExternalStorage_pref = findPref("writeExternalStorage");
    String externalStorageUri = FsSettings.getExternalStorageUri();
    if (externalStorageUri == null) {
        writeExternalStorage_pref.setChecked(false);
    }
    writeExternalStorage_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        if ((boolean) newValue) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            startActivityForResult(intent, ACTION_OPEN_DOCUMENT_TREE);
            return false;
        } else {
            FsSettings.setExternalStorageUri(null);
            return true;
        }
    });

    ListPreference theme = findPref("theme");
    theme.setSummary(theme.getEntry());
    theme.setOnPreferenceChangeListener((preference, newValue) -> {
        theme.setSummary(theme.getEntry());
        getActivity().recreate();
        return true;
    });

    Preference help = findPref("help");
    help.setOnPreferenceClickListener(preference -> {
        Cat.v("On preference help clicked");
        Context context = getActivity();
        AlertDialog ad = new AlertDialog.Builder(context).setTitle(R.string.help_dlg_title)
                .setMessage(R.string.help_dlg_message).setPositiveButton(android.R.string.ok, null).create();
        ad.show();
        Linkify.addLinks((TextView) ad.findViewById(android.R.id.message), Linkify.ALL);
        return true;
    });

    Preference about = findPref("about");
    about.setOnPreferenceClickListener(preference -> {
        startActivity(new Intent(getActivity(), AboutActivity.class));
        return true;
    });

}

From source file:tf.nox.wifisetup.WifiSetup.java

private void saveWifiConfig() {
    WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);/*from  w w  w  .j av a 2s .c  om*/

    WifiConfiguration currentConfig = new WifiConfiguration();

    List<WifiConfiguration> configs = null;
    for (int i = 0; i < 10 && configs == null; i++) {
        configs = wifiManager.getConfiguredNetworks();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            continue;
        }
    }

    if (check5g.isChecked()) {
        ssid = "34C3";
    } else {
        ssid = "34C3-legacy";
    }
    subject_match = "/CN=radius.c3noc.net";
    altsubject_match = "DNS:radius.c3noc.net";

    s_username = username.getText().toString();
    s_password = password.getText().toString();
    realm = "";
    if (s_username.equals("") && s_password.equals("")) {
        s_username = "34c3";
        s_password = "34c3";
    } else {
        if (s_username.indexOf("@") >= 0) {
            int idx = s_username.indexOf("@");
            realm = s_username.substring(idx);
        }
    }

    // Use the existing eduroam profile if it exists.
    boolean ssidExists = false;
    if (configs != null) {
        for (WifiConfiguration config : configs) {
            if (config.SSID.equals(surroundWithQuotes(ssid))) {
                currentConfig = config;
                ssidExists = true;
                break;
            }
        }
    }

    currentConfig.SSID = surroundWithQuotes(ssid);
    currentConfig.hiddenSSID = false;
    currentConfig.priority = 40;
    currentConfig.status = WifiConfiguration.Status.DISABLED;

    currentConfig.allowedKeyManagement.clear();
    currentConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);

    // GroupCiphers (Allow most ciphers)
    currentConfig.allowedGroupCiphers.clear();
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

    // PairwiseCiphers (CCMP = WPA2 only)
    currentConfig.allowedPairwiseCiphers.clear();
    currentConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

    // Authentication Algorithms (OPEN)
    currentConfig.allowedAuthAlgorithms.clear();
    currentConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

    // Protocols (RSN/WPA2 only)
    currentConfig.allowedProtocols.clear();
    currentConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

    // Enterprise Settings
    HashMap<String, String> configMap = new HashMap<String, String>();
    configMap.put(INT_SUBJECT_MATCH, subject_match);
    configMap.put(INT_ALTSUBJECT_MATCH, altsubject_match);
    configMap.put(INT_ANONYMOUS_IDENTITY, "anonymous" + realm);
    configMap.put(INT_IDENTITY, s_username);
    configMap.put(INT_PASSWORD, s_password);
    configMap.put(INT_EAP, "TTLS");
    configMap.put(INT_PHASE2, "auth=PAP");
    configMap.put(INT_ENGINE, "0");
    // configMap.put(INT_CA_CERT, INT_CA_PREFIX + ca_name);

    applyAndroid43EnterpriseSettings(currentConfig, configMap);

    if (!ssidExists) {
        int networkId = wifiManager.addNetwork(currentConfig);
        wifiManager.enableNetwork(networkId, false);
    } else {
        wifiManager.updateNetwork(currentConfig);
        wifiManager.enableNetwork(currentConfig.networkId, false);
    }
    wifiManager.saveConfiguration();

}

From source file:nl.nikhef.eduroam.WiFiEduroam.java

private void saveWifiConfig() {
    WifiManager wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);/*from  w  w w.  j  a va2  s .  co m*/

    WifiConfiguration currentConfig = new WifiConfiguration();

    List<WifiConfiguration> configs = null;
    for (int i = 0; i < 10 && configs == null; i++) {
        configs = wifiManager.getConfiguredNetworks();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            continue;
        }
    }

    // Use the existing eduroam profile if it exists.
    boolean ssidExists = false;
    if (configs != null) {
        for (WifiConfiguration config : configs) {
            if (config.SSID.equals(surroundWithQuotes(ssid))) {
                currentConfig = config;
                ssidExists = true;
                break;
            }
        }
    }

    currentConfig.SSID = surroundWithQuotes(ssid);
    currentConfig.hiddenSSID = false;
    currentConfig.priority = 40;
    currentConfig.status = WifiConfiguration.Status.DISABLED;

    currentConfig.allowedKeyManagement.clear();
    currentConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);

    // GroupCiphers (Allow most ciphers)
    currentConfig.allowedGroupCiphers.clear();
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

    // PairwiseCiphers (CCMP = WPA2 only)
    currentConfig.allowedPairwiseCiphers.clear();
    currentConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

    // Authentication Algorithms (OPEN)
    currentConfig.allowedAuthAlgorithms.clear();
    currentConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

    // Protocols (RSN/WPA2 only)
    currentConfig.allowedProtocols.clear();
    currentConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

    // Enterprise Settings
    HashMap<String, String> configMap = new HashMap<String, String>();
    configMap.put(INT_SUBJECT_MATCH, subject_match);
    configMap.put(INT_ANONYMOUS_IDENTITY, "anonymous" + realm);
    configMap.put(INT_EAP, "TLS");
    configMap.put(INT_ENGINE, "1");
    configMap.put(INT_ENGINE_ID, "keystore");
    configMap.put(INT_CA_CERT, INT_CA_PREFIX + ca_name);
    configMap.put(INT_PRIVATE_KEY, INT_PRIVATE_KEY_PREFIX + client_cert_name);
    configMap.put(INT_PRIVATE_KEY_ID, INT_PRIVATE_KEY_ID_PREFIX + client_cert_name);
    configMap.put(INT_CLIENT_CERT, INT_CLIENT_CERT_PREFIX + client_cert_name);

    if (android.os.Build.VERSION.SDK_INT >= 11 && android.os.Build.VERSION.SDK_INT <= 17) {
        applyAndroid4_42EnterpriseSettings(currentConfig, configMap);
    } else if (android.os.Build.VERSION.SDK_INT >= 18) {
        applyAndroid43EnterpriseSettings(currentConfig, configMap);
    } else {
        throw new RuntimeException("API version mismatch!");
    }

    if (!ssidExists) {
        int networkId = wifiManager.addNetwork(currentConfig);
        wifiManager.enableNetwork(networkId, false);
    } else {
        wifiManager.updateNetwork(currentConfig);
        wifiManager.enableNetwork(currentConfig.networkId, false);
    }
    wifiManager.saveConfiguration();

}