即使移动数据在 Android M 上打开(有连接),也可以通过 WiFi(无连接)发送请求 [英] Send request over WiFi (without connection) even if Mobile data is ON (with connection) on Android M

查看:30
本文介绍了即使移动数据在 Android M 上打开(有连接),也可以通过 WiFi(无连接)发送请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在没有互联网连接的情况下将 UDP 数据包发送到 WiFi 模块(随自己的 AP 提供),但是当我将移动设备与 AP 连接时,Android 会将我的数据包重定向到移动数据接口上,因为它已连接到互联网.

I have to send UDP packets to a WiFi module (provided with own AP) with no internet connection but when I connect the mobile with the AP, Android redirects my packets on the mobile data interface because it has got internet connection.

我使用下面的代码来完成我的工作,但它似乎不适用于 Android M.

I've used the code below to do my job but it seems not working on Android M.

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setWifiInterfaceAsDefault() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkRequest.Builder builder = new NetworkRequest.Builder();
    NetworkRequest networkRequest= builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .build();

    connectivityManager.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback());
}

我也添加了

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

在我的 AndroidManifest.xml 上,我确保自己 Settings.System.canWrite(this) 返回 true 但仍然没有.

on my AndroidManifest.xml and I ensured myself that Settings.System.canWrite(this) returns true but still nothing.

提前致谢.

推荐答案

使用 ConnectivityManager.setProcessDefaultNetwork() 绑定网络可防止漫游并允许完全 TCP 访问.因此,在 onAvailable() 回调中,您可以将应用程序进程绑定到该网络,而不是打开与特定 URL 的连接.

Bind the network using ConnectivityManager.setProcessDefaultNetwork() prevents roaming and allows for full TCP access. Thus, within the onAvailable() callback you could bind the application process to that network rather than opening a connection to a particular URL.

ConnectivityManager connection_manager = 
(ConnectivityManager) activity.getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkRequest.Builder request = new NetworkRequest.Builder();
request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);

connection_manager.registerNetworkCallback(request.build(), new NetworkCallback() {

    @Override
    public void onAvailable(Network network) {
        ConnectivityManager.setProcessDefaultNetwork(network);
    }
}

原答案

这篇关于即使移动数据在 Android M 上打开(有连接),也可以通过 WiFi(无连接)发送请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆