In my opinion what you want is a broadcast receiver that receives the connectivity changes broadcast. When you receive a broadcast, you determine whether the device is then connected to a network, and then try to make the TCP connection to the server. When the device changes networks, from Wifi to 3g/4g or vice versa, this receiver should receive broadcasts.
Here is an example of what I use for such use cases:
public class InternetStatusListener extends BroadcastReceiver {
private static final String TAG="INTERNET_STATUS";
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "network status changed");
if(InternetStatusListener.isOnline(context)){//check if the device has an Internet connection
//Start a service that will make your TCP Connection.
}
}
}
public static boolean isOnline(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
I hope this helps you. There maybe other better ways, but this is what I use.
Also, you have to add these to your android manifest file:
<receiver
android:name=".InternetStatusListener"
android:label="InternetStatusListener" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
<!-- Put these permissions too.-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />