Send HTTP request through 3G network without using WiFi?

前端 未结 1 702
旧时难觅i
旧时难觅i 2021-02-11 03:44

First of all, Android phone is connected both 3G network and wifi. At this time I\'d like to send http request through 3G network without using wifi. How can I do it?

1条回答
  •  失恋的感觉
    2021-02-11 04:25

    I don't think you can do this because in Android only one Network is active at any point of time. So for that first you need to check which network is active and then if it is a Wi-Fi one, then disconnect it, then Android will fallback to other one which will be 3G (if there is no other wi-fi network available), then you can send your request which will go through 3G network.outline might look like this:

    ConnectivityManager cm = (ConnectivityManager)Context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if(ni == null)
      //no connectivity, abort
    if(ni.getType() == ConnectivityManager.TYPE_WIFI || ni.getType() == ConnectivityManager.TYPE_WIMAX) {
      WifiManager wm = (WifiManager)Context.getSystemService(Context.WIFI_SERVICE);
      if( wm != null)
        wm.disconnect();
      //this will force android to fallback to other available n/w which is 3G
    }
    while(true) {
      NetworkInfo ni = cm.getActiveNetworkInfo();
      if( ni != null && ni.getType() == ConnectivityManager.TYPE_MOBILE && ni.isConnected()) {
        //send your http request
        break;
      }
      //sleep for some time, so that android can connect you to other n/w
    }
    You might need to loop through all active n/w and disconnect them till you find 3G network. I am assuming that there is just one Wi-Fi network and one 3G network available.

    0 讨论(0)
提交回复
热议问题