Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use mobile data for sending requests when connected to a Wi-Fi without internet (Android/iOS)?

The app connects to a Wi-Fi network (ELM327) to collect car data, but this network has no internet access. Need to send data via mobile network simultaneously.

Problem: On Android/iOS, when Wi-Fi is active, all traffic uses it by default, even if there’s no internet. How to force HTTP requests to use mobile data without disconnecting Wi-Fi?

like image 396
Petr Avatar asked Nov 17 '25 06:11

Petr


1 Answers

Android Solution

Android allows developers to direct specific traffic through the mobile network, even while connected to Wi-Fi.

Connect to the Wi-Fi network (ELM327) for collecting car data.

Use the ConnectivityManager to access the mobile network interface.

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkRequest.Builder requestBuilder = new NetworkRequest.Builder();
requestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);

cm.requestNetwork(requestBuilder.build(), new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(Network network) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            cm.bindProcessToNetwork(network);
        } else {
            ConnectivityManager.setProcessDefaultNetwork(network);
        }

        // Place your HTTP request code here, it will use mobile data.
    }
});

After completing the requests, you can unbind the network by calling:

cm.bindProcessToNetwork(null);
like image 79
user607464 Avatar answered Nov 18 '25 19:11

user607464



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!