Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...