how to programmatically determine if android is connected to wifi?

元气小坏坏 提交于 2019-12-05 13:38:00

Send a "ping" if you want to call it that. If the connection completes, you know you are still connected. If you get an IOException or a NullPointerException, then you probably timed out and are not connected anymore.

try {
        URL url = new URL("http://www.google.com");
        HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
        urlConnect.setConnectTimeout(1000);
        urlConnect.getContent();
        System.out.println("Connection established.");
    } catch (NullPointerException np) {
        np.printStackTrace();
    } catch (IOException io) {
        io.printStackTrace();
    }

Instead of getting the networkinfo manually... try getting the 'currently active' network and checking if that is the wifi. Note: If it is null that means that no network is connected... so it replaces the isConnected call.

ConnectivityManager connManager = 
    (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo current = connManager.getActiveNetworkInfo();
boolean isWifi = current != null && current.getType() == ConnectivityManager.TYPE_WIFI;
Syd

wifiManager.getWifiState()== WifiManager.WIFI_STATE_ENABLED when you get full connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!