单击按钮后,我使用下面的代码连接到已定义的SSID Wifi网络。它已连接,但在2到3秒钟后,wifi切换回了最初连接的AP。虽然我选择的AP具有更好的信号强度。是否需要在代码中添加任何其他行来保留使用代码激活的AP。
wifiManager.disconnect();
for (WifiConfiguration wifiConfiguration : wifiManager.getConfiguredNetworks()) {
Log.i(TAG, wifiConfiguration.SSID);
if (wifiConfiguration.SSID.equalsIgnoreCase("\"" + "AHGE" + "\"")) {
Log.e(TAG, "Match");
if (wifiManager.enableNetwork(wifiConfiguration.networkId, true)) {
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
}
return;
} else {
Log.e(TAG, "NO Match");
}
}
以下是清单中的权限:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />