Android, How to handle change in network (from GPRS to Wi-fi and vice-versa) while polling for data
Asked Answered
I

2

5

I use DefaultHttpClient and HttpGet to poll data from server. Now, say a user was in Wi-fi network and moves out of the room. So the phone automatically starts using the 3G network. Are there any call-backs for such change, and how should I handle such changes. Should I start polling again or does the OS take care to make the changes appropriately

Icelander answered 2/3, 2011 at 8:33 Comment(0)
V
17

You can set up a Receiver in your manifest:

<receiver
  android:name=".NetworkChangeReceiver"
  android:label="NetworkChangeReceiver">
  <intent-filter>
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
  </intent-filter>
</receiver>

And implement the Receiver with something like this:

public class NetworkChangeReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(final Context context, final Intent intent) {
    final ConnectivityManager connMgr = (ConnectivityManager) 
    context.getSystemService(Context.CONNECTIVITY_SERVICE);

    final android.net.NetworkInfo wifi = 
    connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    final android.net.NetworkInfo mobile = 
    connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (wifi.isAvailable()) {
      //Do something
    if (mobile.isAvailable()) {
      //Do something else
    }
  }
}

If you are keeping a persistent connection it will go down and you have to re-establish it.

If you are scheduling a service and you are not keeping the connection persistent, you will not have problems.

Vladivostok answered 16/3, 2011 at 18:21 Comment(0)
B
-3

I think nothing you need to do ,but you should guarantee that your server's IP address is not arranged randomly,that is to say you should have a fixed IP address.That's my answer;

Burstone answered 22/12, 2014 at 3:23 Comment(1)
I think it's more likely that the client (on a mobile device) might change its' IP address. This does not answer OP's question from March of 2011.Coil

© 2022 - 2024 — McMap. All rights reserved.