0

I want to develop a app remains TCP connection to server for a period of time(like one or two minutes) but I have to consider device's IP changed since client might be moving during this period. so I wonder how can we determine if a Android device has changed its network environment (goes from Wifi to 4G or vise versa) especially device's public IP changed due to any network environment has been changed?

thanks

Korben
  • 734
  • 1
  • 7
  • 26
  • 1
    If your IP changes you will be disconnected. – user253751 Feb 26 '15 at 03:47
  • refer to [This SO post](http://stackoverflow.com/questions/2802472/detect-network-connection-type-on-android) – Randyka Yudhistira Feb 26 '15 at 03:48
  • @immibis I want to ask Android to reconnect if connection was re-established. in case when a client changed cell tower because it keeps moving (using 4G service in a car probably, or wifi goes off and 4G took place) IP will likely to be changed. this can only be done at Client side. how can we do that in such case? – Korben Feb 26 '15 at 03:53

1 Answers1

5

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" />
jonDoe
  • 268
  • 1
  • 12