How to use data connection instead of WIFI when both are on?

Both Wi-Fi and data connections are allowed. Since I need to use mobile data to send an HTTP request to a mobile operator to get a phone number, but android will use Wi-Fi as before, so how can I use a data connection instead of WIFI?

When I turn on Wi-Fi and mobile data in the device. I use the method getAllNetworks(), but it always returns wifi. I dont know. Why does getAllNetworks just return Wi-Fi when I turn on both Wi-Fi and mobile data?

When I simply turn on mobile data, it getAllNetworks()returns information about mobile data.

ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] network = connectivityManager.getAllNetworks();
if(network != null && network.length >0 ){
     for(int i = 0 ; i < network.length ; i++){
          NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network[i]);
          int networkType = networkInfo.getType();
          if(ConnectivityManager.TYPE_MOBILE == networkType ){
               connectivityManager.bindProcessToNetwork(network[i]);
          }
     }
}

- , WIFI, Wi-Fi ?

+4
2

, WIFI, Android Lollipop.

, Android Lollipop API 23, bindProcessToNetwork setProcessDefaultNetwork.

Android Lollipop .

ConnectivityManager cm;
    cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkRequest.Builder req = new NetworkRequest.Builder();
    req.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    req.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
    cm.requestNetwork(req.build(), new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
              //here you can use bindProcessToNetwork
        }

    });

, , !

+11

Source: https://habr.com/ru/post/1606112/


All Articles