我正在学习WifiManager,WifiConfiguration API
我想要实现的是我想连接到特定的网络
这是我连接特定网络的主要任务,但是如果我的设备已经连接到其他网络,我想从网络切换到我的特定网络。
这是片段
int networkId ;
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "ABCDEFG";
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
Log.d("Rohit", "Adding wifi config");
networkId = wifiManager.addNetwork(wc);
Log.d("Rohit", "Config added\ndisconnecting\nid = "+networkId);
wifiManager.disconnect();
Log.d("Rohit", "Disconnected\nNetwork enabling");
wifiManager.enableNetwork(networkId, true);
Log.d("Rohit", "enabled\n reconnecting....");
wifiManager.reconnect();
Log.d("Rohit","connected");
这是调试输出
04-08 19:57:49.690 3326-3326 / com.example.illuminati.services D / Rohit:添加wifi配置 04-08 19:57:49.964 3326-3326 / com.example.illuminati.services D / Rohit:已添加配置 04-08 19:57:49.964 3326-3326 / com.example.illuminati.services D / Rohit:断开连接 04-08 19:57:49.964 3326-3326 / com.example.illuminati.services D / Rohit:id = 64 04-08 19:57:49.964 3326-3326 / com.example.illuminati.services D / Rohit:断开连接 04-08 19:57:49.964 3326-3326 / com.example.illuminati.services D / Rohit:网络启用 04-08 19:57:50.087 3326-3326 / com.example.illuminati.services D / Rohit:启用 04-08 19:57:50.087 3326-3326 / com.example.illuminati.services D / Rohit:重新连接.... 04-08 19:57:50.089 3326-3326 / com.example.illuminati.services D / Rohit:已连接
如果设备未连接到任何网络,则它会连接到SPECIFIC NETWORK 但如果它连接到其他网络,它将再次重新连接到同一网络 我在这里缺少什么? 我在stackoverflow中发现了一个类似的问题,但这并没有帮助 任何帮助将不胜感激:)
答案 0 :(得分:0)
好的经过30-40分钟的测试后,这对我来说很有用 我创建了一个单独的方法来禁用当前活动的网络 但有一点我不明白在wifiManager.enableNetwork(networkId,true);第二个参数是disableOthers 所以,如果我使用wifiManager.enableNetwork(networkId,true); ,它应该做我在单独方法中完成的技巧 想法?
这是更新后的代码
int networkId ;
wifiConfig = getWifiConfig();
wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
// if(wifiManager.)
WifiInfo info = wifiManager.getConnectionInfo();
Log.d("Rohit", "current ssid "+info.getSSID());
boolean disable =disableCurrent(info.getSSID());
// Log.d("Rohit","disabled ?"+disable);
Log.d("Rohit", "Adding wifi config");
networkId = wifiManager.addNetwork(wifiConfig);
//wifiManager.enableNetwork(networkId, true);
wifiManager.disconnect();
Log.d("Rohit", "Config added\ndisconnecting\nid = " + networkId);
wifiManager.enableNetwork(networkId, true);
Log.d("Rohit", "Disconnected\nNetwork enabling");
Log.d("Rohit", "enabled\n reconnecting....");
wifiManager.reconnect();
Log.d("Rohit", "connected");
这是单独的方法
public boolean disableCurrent(String ssid)
{
List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
for(WifiConfiguration conf : configuredNetworks)
{
Log.d("Rohit","List "+conf.SSID);
if(conf.SSID.equals(ssid)) {
Log.d("Rohit","Inside");
wifiManager.disableNetwork(conf.networkId);
return true;
}
}
return false;
}