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

后端 未结 2 810
既然无缘
既然无缘 2020-12-03 02:08

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

2条回答
  •  一个人的身影
    2020-12-03 02:38

    You can set up a Receiver in your manifest:

    
      
        
        
      
    
    

    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.

提交回复
热议问题