Android(安卓)Wifi 信息保存与忘记
16lz
2021-01-26
最近在做项目的时候,遇到一个需求,在某一个页面内需要连接指定Wifi,当退出这个页面时需要恢复原来的网络状态。于是就想到了退出页面时忘记此时连接的指定wifi。于是,代码开始了
WifiManager mWifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE); mWifiManager.forget()...
等等,为什么forget是红色的,没提示呢???惊叹三秒钟只有赶紧回源码查看,原来是这样的
/** * Delete the network in the supplicant config. * * This function is used instead of a sequence of removeNetwork() * and saveConfiguration(). * * @param config the set of variables that describe the configuration, * contained in a {@link WifiConfiguration} object. * @param listener for callbacks on success or failure. Can be null. * @throws IllegalStateException if the WifiManager instance needs to be * initialized again * @hide */ public void forget(int netId, ActionListener listener) { if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative"); getChannel().sendMessage(FORGET_NETWORK, netId, putListener(listener)); }
看到这个@hide了没,原来这方法被隐藏掉了,看来要用只能用反射了啊,可是还是不甘心,不想用反射,于是就继续找啊找啊,于是在这个方法的注释里找到了这个:
* This function is used instead of a sequence of removeNetwork() * and saveConfiguration().
好吧,我们就看看removeNetwork(),
/** * Remove the specified network from the list of configured networks. * This may result in the asynchronous delivery of state change * events. * @param netId the integer that identifies the network configuration * to the supplicant * @return {@code true} if the operation succeeded */ public boolean removeNetwork(int netId) { try { return mService.removeNetwork(netId); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } }
看了上面的注释,大伙都应该明白了。于是问题完美解决,同样的save也用saveConfiguration()替代
/** * Tell the supplicant to persist the current list of configured networks. * * Note: It is possible for this method to change the network IDs of * existing networks. You should assume the network IDs can be different * after calling this method. * * @return {@code true} if the operation succeeded */
public boolean saveConfiguration() { try { return mService.saveConfiguration(); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } }
好了,就这样,再查资料的时候找到了有些博客,命名上面方法写的@hide,下面代码还是用forget,不知道最后成功了没。。。
欢迎不同意见的朋友一起留言讨论,共同学习进步。
更多相关文章
- Android通信方式(一)————WebView
- Android:Activity(六):Fragment详解
- android kotlin webview内H5调用微信支付问题
- 简单理解View的onMeasure过程
- Binder通信机制
- Android知识点(自己版)
- Android网络访问的基本方法
- Android中保存和恢复Fragment状态的最好方法
- Android文件存储--采用SharedPreferences保存用户偏好设置参数和