If you want both operation to work on a single button click, then add a BroadcastReceiver
for listening to Wifi connection state, as shown in below. & in the onReceive()
method do the socket connection. Your socket connection is not working when in same button click because Wifi connection takes time & without first Wifi being connected socket connection is being created, so it might throw an exception.
Checking for whether Wi-Fi is enabled, that doesn't necessarily mean that it's connected. It just means that Wi-Fi mode on the phone is enabled and able to connect to Wi-Fi networks.
This is how listening for actual Wi-Fi connections in Broadcast Receiver:
public class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
Log.d("WifiReceiver", "Have Wifi Connection");
//If connected do socket connection here
}
else
Log.d("WifiReceiver", "Don't have Wifi Connection");
}
};
In order to access the active network info you need to add the following uses-permission to your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And the following intent receiver (or you could add this programmatically...)
<!-- Receive Wi-Fi connection state changes -->
<receiver android:name=".WifiReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
& make sure that network activity is done on other thread than Main thread. Also you'll have to register & unregister the BroadcastReceiver
appropriately. Don't forget to unregister it when not needed.