gpt4 book ai didi

android - 如何在连接 WiFi 的情况下使用移动数据服务?

转载 作者:行者123 更新时间:2023-11-30 05:05:40 24 4
gpt4 key购买 nike

我正在开发一个测试应用程序,它必须能够选择 WiFi 或移动数据服务。以下代码显示 WiFi 和移动网络均已连接,但 bindProcessToNetwork() 在移动网络上失败。

public class MyActivity extends AppCompatActivity {
private ConnectivityManager mConnMgr = null;
private Network mNetworkWiFi = null;
private Network mNetworkMobile = null;

mConnMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isWifiConn = false;
boolean isMobileConn = false;
for (Network network : mConnMgr.getAllNetworks()) {
NetworkInfo networkInfo = mConnMgr.getNetworkInfo(network);

if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
isWifiConn = networkInfo.isConnected();
mNetworkWiFi = network;
}
if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
isMobileConn = networkInfo.isConnected();
mNetworkMobile = network;
}
}

if (mNetworkMobile && mConnMgr.getNetworkInfo(mNetworkMobile).isConnected()) {
if (true != mConnMgr.bindProcessToNetwork(mNetworkMobile)) {
Log.i(TAG, "Failed to bind to Mobile");
}
}

问题:1. bindProcessToNetwork() 是在WiFi和Mobile之间选择数据服务的正确方法吗?2. 什么可能导致 bindProcessToNetwork() 在连接的移动网络上失败?

最佳答案

下面的代码让我在连接 WiFi 时使用移动数据服务:

                final NetworkRequest networkReq = new NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR).build();
mConnMgr.requestNetwork(networkReq, new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
Log.i(TAG, "Requested netwwork available: " + network.toString());
if (true != mConnMgr.bindProcessToNetwork(network)) {
Log.i(TAG, "Failed to bind to Mobile");
}

}
});

关于android - 如何在连接 WiFi 的情况下使用移动数据服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54641195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com