admin管理员组

文章数量:1388153

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?

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?

Share Improve this question asked Mar 18 at 8:00 PetrPetr 2542 silver badges16 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 4

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);

本文标签: