Android 切换wifi小记
我手机是Android 7.1的魅族.相关网络权限注册之后,还有一个特别的权限就是<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />搞不懂开wifi与位置权限有啥关系。
一些基本配置方法网上都有,但有一个注意点,就是切换wifi时,通常会出现netid=-1的情况,是因为要连接的wifi是以前连接过的,通过WifiManager.getConfiguredNetworks();来获得已配置过的wifi的netid,但你当前已经连接了wifi,所以必须 WifiManager.disableNetwork(mWifiInfo.getNetworkId());先使当前连接的wifi不可用,然后再连接才行,不然手机老是切不了。因为需要切换之前判断要连接的wifi是否已配置过,如果配置过,则直接enableNetwoke(获得的已配置nedid,ture),否则,添加wifi,然后enable即可。
//判断wifi曾经是不是连接过 WifiConfiguration tempConfig = isExsits(ssid); if (tempConfig != null) { boolean enabled = wifiManager.enableNetwork(tempConfig.networkId, true); Log.d(TAG, "enableNetwork status enable=" + enabled); } else { int netID = wifiManager.addNetwork(wifiConfig); boolean enabled = wifiManager.enableNetwork(netID, true); Log.d(TAG, "enableNetwork status enable=" + enabled); }
private WifiConfiguration isExsits(String SSID) { if (wifiManager != null) { List<WifiConfiguration> existingConfigs = wifiManager .getConfiguredNetworks(); for (WifiConfiguration existingConfig : existingConfigs) { if (existingConfig.SSID.equals("\"" + SSID + "\"")) { return existingConfig; } } } return null; }
我在使用getConfiguredNetworks时,会出现Add permission check的提示,需要加上:
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return null; }
本文来自博客园,作者:pie_thn,转载请注明原文链接:https://www.cnblogs.com/pie-o/p/14590357.html