Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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

1 Answer

0 votes
by (46k points)

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" />

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...