Send request over Mobile data when WIFI is ON.(Android L)

ぃ、小莉子 提交于 2019-11-27 17:27:24
NitZRobotKoder

Well finally found solution for this. Trick was to use capability as NET_CAPABILITY_INTERNET. Which is same as startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, FEATURE_ENABLE_HIPRI);

See the Firmware design here

builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);

After this I am able to get onAvailable callback from system and later I set my process default network as mobile data.

Hence all the request goes over mobile data even if wifi is on. WOW!

Note: This was not working in initial releases of Preview L.

Edit 19-10-2015: setProcessDefaultNetwork is now depcreated use bindProcessToNetwork

Here's a function that can simplify the action of preferring certain types of networks for your application (should work for any current API level (26 as of writing):

private void alwaysPreferNetworksWith(@NonNull int[] capabilities, @NonNull int[] transportTypes) {

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

    // add capabilities
    for (int cap: capabilities) {
        request.addCapability(cap);
    }

    // add transport types
    for (int trans: transportTypes) {
        request.addTransportType(trans);
    }

    final ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(CONNECTIVITY_SERVICE);

    connectivityManager.registerNetworkCallback(request.build(), new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            try {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                    ConnectivityManager.setProcessDefaultNetwork(network);
                } else {
                    connectivityManager.bindProcessToNetwork(network);
                }
            } catch (IllegalStateException e) {
                Log.e(TAG, "ConnectivityManager.NetworkCallback.onAvailable: ", e);
            }
        }
    });
}

Usage:

// Add any NetworkCapabilities.NET_CAPABILITY_...
int[] capabilities = new int[]{ NetworkCapabilities.NET_CAPABILITY_INTERNET };

// Add any NetworkCapabilities.TRANSPORT_...
int[] transportTypes = new int[]{ NetworkCapabilities.TRANSPORT_CELLULAR };

alwaysPreferNetworksWith(capabilites, transportTypes);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!