Pergunta

All- I have an app in which I want the user to be able to connect with a WiFi network. I looked at this question and I had the app being able to disconnect and than reconnect (in other words I had the right SSID and password), but his is not exactly what I want to do. I want to just connect if not connected already and not do anything if already connected. When I turned WiFi off (via settings) and than ran my app, nothing happened. So than I tried this

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiConfiguration wc = new WifiConfiguration();        
    String networkSSID = SSID;
    String networkPass = PASS;      
    wc.SSID = "\"" + networkSSID + "\""; 
    wc.preSharedKey = "\""+ networkPass +"\"";
    wc.hiddenSSID = true;
    List<WifiConfiguration> list = wifi.getConfiguredNetworks();
    for( WifiConfiguration i : list ) {
        if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {            

        wifi.enableNetwork(i.networkId, true); //Look here

        break;

        }           
     }

versus this

//Above code the same
    for( WifiConfiguration i : list ) {
            if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {            
            wifi.disconnect(); //See, disconnect..
            wifi.enableNetwork(i.networkId, true);
            wifi.reconnect();  //Than reconnect!
            break;

            }           
         }

This change did nothing though (even when the WiFi was on). So my question is how can I just turn WiFi on if not on already and do nothing if already on (I know I have to use if statements so I am just looking for the WiFi specific code)? Thanks for your time!

Foi útil?

Solução

Are you simply asking how to turn on wifi in android programmatically?

How to programmatically turn off WiFi on Android device?

to summarize:

wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 

boolean wifiEnabled = wifiManager.isWifiEnabled();
if(!wifiEnabled){
    wifiManager.setWifiEnabled(true);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top