我正在开发一个测试应用程序,该应用程序必须能够选择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()在连接的移动网络上失败?
答案 0 :(得分:0)
以下代码可让我在连接WiFi时使用MObile数据服务:
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");
}
}
});