Android開發中有時候需要設定程序連接網絡優先 2G/3G 或 WIFI,下面片段代碼給出設置方法:
public void setPreferredNetwork(int networkType) {
ConnectivityManager connMgr = (ConnectivityManager) this.context.getSystemService("connectivity");
if (networkType == NetworkType.TYPE_MOBILE) {//設為2G/3G網絡優先,就算wifi連接到AP,系統仍然通過2G/3G訪問網絡
connMgr.setNetworkPreference(0);
} else if (networkType == NetworkType.TYPE_WIFI) {
connMgr.setNetworkPreference(1);
}
WifiManager wifiMgr = (WifiManager) this.context.getSystemService("wifi");
wifiMgr.disconnect();
}