简体   繁体   中英

How, when wifi and mobile networks are enabled, do you choose to transfer data through the mobile network on android?

Everything practically works, with one exception. If we first assign transmission through mobile data, then everything works well, the data goes through the mobile network. Then I choose wifi data, everything is also good. But if you choose mobile data again after that, then the transfer is already going through wifi, why so? Why does all OK work at the first start, and when wifi is turned on again, data goes through wifi, and not through mobile communication? Who knows the reason? Thank you in advance. Code below.

public void setTransportType(int transportType) {

    connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    if (networkCallback != null) {
        connectivityManager.unregisterNetworkCallback(networkCallback);
        networkCallback = null;
    }

    NetworkRequest.Builder request = new NetworkRequest.Builder();

    if (transportType == TRANSPORT_TYPE_WIFI) {
        request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
    } else {
        request.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
        request.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
    }

    networkCallback = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);

            connectivityManager.bindProcessToNetwork(null);
            connectivityManager.bindProcessToNetwork(network);

            /*Operation after switching over*/
        }

    };

   connectivityManager.requestNetwork(request.build(), networkCallback); 
}

It's because you've bound your connection to the Wifi network with the line:

connectivityManager.bindProcessToNetwork(network);

When you want to switch to using mobile data, you need to reset the bound network:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    manager.bindProcessToNetwork(null);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    ConnectivityManager.setProcessDefaultNetwork(null);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM