最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to use mobile data for sending requests when connected to a Wi-Fi without internet (AndroidiOS)? - Stack Overflow

programmeradmin5浏览0评论

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论