简体   繁体   中英

how to programmatically determine if android is connected to wifi?

I'm trying to setup a test for automation on a new android app that I'm developing but having a bit of trouble with one of the apis

The problem i'm facing is I want to start the test AFTER wifi has a connection, not when its in the connecting state. I have tried two solutions but had no luck and test seems to start before my android device is fully connected (no x on the wifi bars)

wifiManager.setWifiEnabled(state);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
while (wifiInfo.getSSID() == null) {
    Log.i("WifiStatus", "Here I am");
    Thread.sleep(Time.ONE_SECOND);
    wifiInfo = wifiManager.getConnectionInfo();

This is my first implementation trying to get the SSID to determine if connection has been established. but the test still starts before a full connection has been made and fails the setup.

ConnectivityManager connManager = 
    (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

wifiManager.setWifiEnabled(state);
while (!networkInfo.isConnected()) {
    Log.i("WifiStatus", "Here I am");
    Thread.sleep(Time.ONE_SECOND);
    networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}

The second implementation i'm using connectivity manager instead and using isConnected() .

Does anyone have another method I can possibly check to determine if the device has fully established a connection with wifi?

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;

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();
    }

完全连接时wifiManager.getWifiState()== WifiManager.WIFI_STATE_ENABLED

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM