-1

Below I am displaying the current state of the ´WiFi´ network using a textview, but if the current state of the network changes, for example while the App is running and the user turned the WiFi off, the textview would change accordingly. what i am trying to do is, to have a textview that can display the current status of the WiFi network accordingy.

How to achieve this. I hope my question is clear.

Code:

private boolean IsWiFiConnected() {
    // TODO Auto-generated method stub

    ConnectivityManager mconnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mNWInfo = mconnMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (mNWInfo != null) {
        if (mNWInfo.isConnected()) {
            setText(R.id.tv_conn_status, "WiFi is now connected: "+mNWInfo.isConnected());
            return true;
        }else if (mNWInfo.isConnectedOrConnecting()) {
            setText(R.id.tv_conn_status, "WiFi is now connecting/connected: "+mNWInfo.isConnectedOrConnecting());
            return true;
        }else if (mNWInfo.isAvailable()) {
            setText(R.id.tv_conn_status, "WiFi is now available: "+mNWInfo.isAvailable());
            return false;
        }else if (mNWInfo.isFailover()) {
            setText(R.id.tv_conn_status, "WiFi is now in faiover: "+mNWInfo.isFailover());
            return false;
        }else if (mNWInfo.isRoaming()) {
            setText(R.id.tv_conn_status, "WiFi is now available: "+mNWInfo.isRoaming());
            return false;
        }   
    }
    return false;
}
Anirudh Sharma
  • 7,968
  • 13
  • 40
  • 42
Amrmsmb
  • 1
  • 27
  • 104
  • 226

1 Answers1

1

When your app is running, you can register a BroadcastReceiver that will be triggered on changes to the WIFI connectivity. When this happens you can update your view.

See http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html and android.net.wifi.STATE_CHANGE: not triggered on Wifi disconnect

Community
  • 1
  • 1
David Wasser
  • 93,459
  • 16
  • 209
  • 274