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

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


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(capabilities, transportTypes);