我有一个这样的需求,手机连上一个设备发出的WiFi,然后通过手机端修改设备的WiFi账号和密码在进行重连。重连思路是这样的:修改SSID之后重连,那么密码是不变的;修改密码后重连那么账号时不变的,我是这样实现的
package com.ntk.util; import java.util.List; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; public class WifiAdmin { // 定义WifiManager对象 private WifiManager mWifiManager; // 定义WifiInfo对象 private WifiInfo mWifiInfo; // 扫描出的网络连接列表 private List上面是已经封装好的WiFi工具类可以直接使用,其实重连就是这样的,移除当前所连接的WiFi,记住当前连接的账号和密码所以我的操作是这样的mWifiList; // 网络连接列表 private List mWifiConfiguration; // 定义一个WifiLock WifiLock mWifiLock; // 构造器 public WifiAdmin(Context context) { // 取得WifiManager对象 mWifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); // 取得WifiInfo对象 mWifiInfo = mWifiManager.getConnectionInfo(); } // 打开WIFI public void openWifi() { if (!mWifiManager.isWifiEnabled()) { mWifiManager.setWifiEnabled(true); } } // 关闭WIFI public void closeWifi() { if (mWifiManager.isWifiEnabled()) { mWifiManager.setWifiEnabled(false); } } // 检查当前WIFI状态 public int checkState() { return mWifiManager.getWifiState(); } // 锁定WifiLock public void acquireWifiLock() { mWifiLock.acquire(); } // 解锁WifiLock public void releaseWifiLock() { // 判断时候锁定 if (mWifiLock.isHeld()) { mWifiLock.acquire(); } } // 创建一个WifiLock public void creatWifiLock() { mWifiLock = mWifiManager.createWifiLock("Test"); } // 得到配置好的网络 public List getConfiguration() { return mWifiConfiguration; } // 指定配置好的网络进行连接 public void connectConfiguration(int index) { // 索引大于配置好的网络索引返回 if (index > mWifiConfiguration.size()) { return; } // 连接配置好的指定ID的网络 mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true); } public void startScan() { mWifiManager.startScan(); // 得到扫描结果 mWifiList = mWifiManager.getScanResults(); // 得到配置好的网络连接 mWifiConfiguration = mWifiManager.getConfiguredNetworks(); } // 得到网络列表 public List getWifiList() { return mWifiList; } // 查看扫描结果 public StringBuilder lookUpScan() { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < mWifiList.size(); i++) { stringBuilder .append("Index_" + new Integer(i + 1).toString() + ":"); // 将ScanResult信息转换成一个字符串包 // 其中把包括:BSSID、SSID、capabilities、frequency、level stringBuilder.append((mWifiList.get(i)).toString()); stringBuilder.append("/n"); } return stringBuilder; } // 得到MAC地址 public String getMacAddress() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress(); } // 得到接入点的BSSID public String getBSSID() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID(); } // 得到IP地址 public int getIPAddress() { return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress(); } // 得到连接的ID public int getNetworkId() { return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId(); } // 得到WifiInfo的所有信息包 public String getWifiInfo() { return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString(); } // 添加一个网络并连接 public void addNetwork(WifiConfiguration wcg) { int wcgID = mWifiManager.addNetwork(wcg); boolean b = mWifiManager.enableNetwork(wcgID, true); System.out.println("a--" + wcgID); System.out.println("b--" + b); } // 断开指定ID的网络 public void disconnectWifi(int netId) { mWifiManager.disableNetwork(netId); mWifiManager.disconnect(); } //然后是一个实际应用方法,只验证过没有密码的情况: public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type) { WifiConfiguration config = new WifiConfiguration(); config.allowedAuthAlgorithms.clear(); config.allowedGroupCiphers.clear(); config.allowedKeyManagement.clear(); config.allowedPairwiseCiphers.clear(); config.allowedProtocols.clear(); config.SSID = "\"" + SSID + "\""; WifiConfiguration tempConfig = this.IsExsits(SSID); if(tempConfig != null) { mWifiManager.removeNetwork(tempConfig.networkId); } if(Type == 1) //WIFICIPHER_NOPASS { config.wepKeys[0] = ""; config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); config.wepTxKeyIndex = 0; } if(Type == 2) //WIFICIPHER_WEP { config.hiddenSSID = true; config.wepKeys[0]= "\""+Password+"\""; config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); config.wepTxKeyIndex = 0; } if(Type == 3) //WIFICIPHER_WPA { config.preSharedKey = "\""+Password+"\""; config.hiddenSSID = true; config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); //config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); config.status = WifiConfiguration.Status.ENABLED; } return config; } public WifiConfiguration IsExsits(String SSID) { List existingConfigs = mWifiManager.getConfiguredNetworks(); for (WifiConfiguration existingConfig : existingConfigs) { if (existingConfig.SSID.equals("\""+SSID+"\"")) { return existingConfig; } } return null; } }
wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(ssid, resultq.get("passphrase").toString(), 3));这里的关键是你要保存之前所连接的SSID或密码,其实到这里WiFi重连就已经成功了,但是还会碰到很大的问题,一般我们是修改WiFi后点击重连,我们肯定不会在这个期间让用户操作我们的app了吧,所以我加了个dialog进行等待提示,这里又有问题,可能我们的WiFi已经重连成功但是我们的等待提示还在执行。这就尴尬了不用慌,加个监听吗,上代码:
private BroadcastReceiver mReceiver = new BroadcastReceiver (){ @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)){ //signal strength changed } else if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){//wifi连接上与否 System.out.println("网络状态改变"); NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if(info.getState().equals(NetworkInfo.State.DISCONNECTED)){ } else if(info.getState().equals(NetworkInfo.State.CONNECTED)){ WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String ssid = wifiInfo.getSSID(); // setConnect(false); //获取当前wifi名称 // Toast.makeText(getApplicationContext(), "网络连接到"+wifiInfo.getSSID(), Toast.LENGTH_SHORT).show(); if (MyApp.SSID!=null) { deviceVersion = Build.VERSION.SDK_INT; if (deviceVersion >= 17) {//41.系统上的没有引号 if (ssid.startsWith("\"") && ssid.endsWith("\"")) { ssid = ssid.substring(1, ssid.length() - 1); if (ssid.contains(MyApp.SSID)) { //Toast.makeText(getApplicationContext(), "WiFi网络连接成功"+ssid+"----:::"+MyApp.SSID+"", Toast.LENGTH_SHORT).show(); setConnect(false); stopClick(chronometer); isConecting = false; textView_camera_info_SSID.setText(MyApp.SSID); // Toast.makeText(getApplicationContext(), "WiFi连接成功", Toast.LENGTH_SHORT).show(); } } } } }直接拿去用不谢,在这个里面有一点需要注意那就是有的系统你获取到的SSID会带上引号,也许到这里就解决了你的需求,但是我的问题还是没解决,oh NO是不是在想我的问题到底是什么~~~你们有没有想过如果重连时间过长怎么办?这是个很大的问题!!!所以我就想到了20秒后给个提示,让用户自己手动重连,请看下面:
public class OnChronometerTickListenerImpl implements OnChronometerTickListener { // 计时监听事件,随时随地的监听时间的变化 @Override public void onChronometerTick(Chronometer chronometer2) { String time2 = chronometer2.getText().toString(); Log.e("aaaaaaaaa : ", time2); if ("00:00:20".equals(time2)) { setConnect(false); stopClick(chronometer); backWifi(); } } } private void backWifi(){ if(psDialog==null){ psDialog = new ProgressDialog(MenuActivity.this); psDialog.setMessage("WiFi连接失败,请手动连接"); psDialog.setCancelable(false);机制的我使用了Android原生的Chronometer控件,关于这个控件大家可以百度一下,是在不知道的也可以私聊我哦好了,这样就解决了我的需求了,一道20秒就提示用户手动重连,哦了。