使用ConnectivityManager.bindProcessToNetwork绑定特殊网络
最近测试那边提了一个bug,经过排查后发现其原因:是因为连接的Wi-Fi无法上网,因此在Android系统的多网络策略中,可以上网的SIM移动网络被设置为系统默认网络,投屏组件docker传输与反控模块和scbee流媒体传输模块都未绑定Wi-Fi网络,模块进程默认使用系统默认网络,因此无法投屏成功。而P2P投屏不存在此问题,P2P网络属于本地Local局域网,网络路由规则高于系统默认网络,因此不受影响。
解决办法:在投屏组件docker传输与反控模块和scbee流媒体传输模块中新增网络绑定接口,为每次连接指定网络通路。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
public static final int TYPE_DEFAULT = -1;
public static final int TYPE_WIFI_STA = 0;
public static final int TYPE_WIFI_P2P = 1;
public static void bindNetworkToProcess(Context context, int networkType) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
if (null != connManager) {
if (networkType != TYPE_DEFAULT) {
Network[] networkList = connManager.getAllNetworks();
for (Network network : networkList) {
NetworkInfo networkInfo = connManager.getNetworkInfo(network);
if (networkInfo.getType() == networkType) {
LogUtils.d(TAG, "bindNetworkToProcess: " + networkInfo.toString());
connManager.bindProcessToNetwork(network);
return;
}
}
LogUtils.e(TAG, "bindNetworkToProcess not found type: " + networkType);
} else {
connManager.bindProcessToNetwork(null);
LogUtils.d(TAG, "unbindNetworkToProcess");
}
} else {
LogUtils.e(TAG, "bindNetworkToProcess get CONNECTIVITY_SERVICE failed!");
}
}
public static int convertNetworkType(int networkType) {
switch (networkType) {
case Constant.TYPE_WIFI_STA:
return ConnectivityManager.TYPE_WIFI;
case Constant.TYPE_WIFI_P2P:
default:
return Constant.TYPE_DEFAULT;
}
}
调用的地方:
// 绑定网络
Utils.bindNetworkToProcess(getBaseContext(), Utils.convertNetworkType(networkType));
// 取消绑定网络
Utils.bindNetworkToProcess(getBaseContext(), TYPE_DEFAULT);