-2

In my application I'm connecting to the wifi programatically. is there a way for me to display a button upon wifi gettting connected?

Mr.Noob
  • 1,005
  • 3
  • 24
  • 58

2 Answers2

3

You can use this question to tell you if you are connected to wifi. Once you know that you are you can display your button like you normally would.

So your code (taken from Jason Knight's answer) would be:

ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
    // show button 
}
Community
  • 1
  • 1
David says Reinstate Monica
  • 19,209
  • 22
  • 79
  • 122
2

You will need to implement a BroadcastReceiver to listen for network state changes.

private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context c, Intent intent) {
        if (intent.getAction() == WifiManager.NETWORK_STATE_CHANGED_ACTION) {
            Bundle extras = Intent.getExtras();
            NetworkInfo ni = extras.get(EXTRA_NETWORK_INFO);
            if (ni.getState() == State.CONNECTED) {
                //show button
            } else {
                //hide button
            }
        } else if (intent.getAction() == WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION) {
            Bundle extras = Intent.getExtras();
            SupplicantState ss = extras.get(EXTRA_NEW_STATE);
            if (ss.getState() == COMPLETED) {
                //show button, note we may not have an IP address yet
            } else {
                //hide button
            }
            SupplicantState.COMPLETED
        }
    }
};

and, somewhere in the OnCreate() method of the Activitys that will display the button:

mWifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);

//to listen to all network state changes (cell and wifi)
registerReceiver(mWifiScanReceiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));

//to listen specifically to wifi changes
registerReceiver(mWifiScanReceiver, new IntentFilter(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION));
user149408
  • 5,385
  • 4
  • 33
  • 69