Java Code Examples for android.net.wifi.WifiManager#reconnect()

The following examples show how to use android.net.wifi.WifiManager#reconnect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConnectorUtils.java    From WifiUtils with Apache License 2.0 5 votes vote down vote up
@RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
private static boolean connectToConfiguredNetwork(@Nullable WifiManager wifiManager, @Nullable WifiConfiguration config, boolean reassociate) {
    if (config == null || wifiManager == null) {
        return false;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return disableAllButOne(wifiManager, config) && (reassociate ? wifiManager.reassociate() : wifiManager.reconnect());
    }

    // Make it the highest priority.
    int newPri = getMaxPriority(wifiManager) + 1;
    if (newPri > MAX_PRIORITY) {
        newPri = shiftPriorityAndSave(wifiManager);
        config = ConfigSecurities.getWifiConfiguration(wifiManager, config);
        if (config == null) {
            return false;
        }
    }

    // Set highest priority to this configured network
    config.priority = newPri;
    int networkId = wifiManager.updateNetwork(config);
    if (networkId == -1) {
        return false;
    }

    // Do not disable others
    if (!wifiManager.enableNetwork(networkId, false)) {
        return false;
    }

    if (!wifiManager.saveConfiguration()) {
        return false;
    }

    // We have to retrieve the WifiConfiguration after save.
    config = ConfigSecurities.getWifiConfiguration(wifiManager, config);
    return config != null && disableAllButOne(wifiManager, config) && (reassociate ? wifiManager.reassociate() : wifiManager.reconnect());
}
 
Example 2
Source File: PNetwork.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
@PhonkMethod(description = "Connect to mContext given Wifi network with mContext given 'wpa', 'wep', 'open' type and mContext password", example = "")
@PhonkMethodParam(params = {"ssidName", "type", "password"})
public void connectWifi(String networkSSID, String type, String networkPass) {

    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String
    // should contain ssid in quotes

    if (type.equals("wep")) {
        // wep
        conf.wepKeys[0] = "\"" + networkPass + "\"";
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    } else if (type.equals("wpa")) {
        // wpa
        conf.preSharedKey = "\"" + networkPass + "\"";
    } else if (type.equals("open")) {
        // open
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    }

    WifiManager wifiManager = (WifiManager) getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifiManager.addNetwork(conf);

    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    for (WifiConfiguration i : list) {
        if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
            wifiManager.disconnect();
            wifiManager.enableNetwork(i.networkId, true);
            wifiManager.reconnect();

            break;
        }
    }

}
 
Example 3
Source File: WiFiProxyUtil.java    From WiFiProxySwitcher with Apache License 2.0 5 votes vote down vote up
/**
 * 低于 Android 5.0 系统使用
 */
private boolean unsetWiFiProxySettings4() {
    WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiConfiguration config = getCurrentWifiConfiguration(manager);
    if (null == config)
        return false;

    try {
        // 获得 linkProperties
        Object linkProperties = getField(config, "linkProperties");
        if (null == linkProperties)
            return false;

        // 获得 setHttpProxy 方法
        Class proxyPropertiesClass = Class.forName("android.net.ProxyProperties");
        Class[] setHttpProxyParams = new Class[1];
        setHttpProxyParams[0] = proxyPropertiesClass;
        Class<?> lpClass = Class.forName("android.net.LinkProperties");
        Method setHttpProxy = lpClass.getDeclaredMethod("setHttpProxy", setHttpProxyParams);
        setHttpProxy.setAccessible(true);

        // 参数传递空, 表示取消 proxy 设置
        Object[] params = new Object[1];
        params[0] = null;
        setHttpProxy.invoke(linkProperties, params);

        setProxySettings("NONE", config);

        // 保存设置
        manager.updateNetwork(config);
        manager.disconnect();
        manager.reconnect();

        ToastUtil.showToast(context, "取消Proxy设置成功");
        return true;
    } catch (Exception e) {
        ToastUtil.showToast(context, "取消Proxy设置失败");
        return false;
    }
}
 
Example 4
Source File: WiFiProxyUtil.java    From WiFiProxySwitcher with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private boolean unSetWiFiProxySettings5() {
    try {
        WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiConfiguration config = getCurrentWifiConfiguration(manager);
        Class proxySettings = Class.forName("android.net.IpConfiguration$ProxySettings");

        Class[] setProxyParams = new Class[2];
        setProxyParams[0] = proxySettings;
        setProxyParams[1] = ProxyInfo.class;

        Method setProxy = WifiConfiguration.class.getDeclaredMethod("setProxy", setProxyParams);
        setProxy.setAccessible(true);

        Object[] methodParams = new Object[2];
        methodParams[0] = Enum.valueOf(proxySettings, "NONE");
        methodParams[1] = null;

        setProxy.invoke(config, methodParams);

        manager.updateNetwork(config);
        manager.disconnect();
        manager.reconnect();

        ToastUtil.showToast(context, "取消Proxy设置成功");
        return true;
    } catch (Exception e) {
        ToastUtil.showToast(context, "取消Proxy设置失败");
        return false;
    }
}
 
Example 5
Source File: WiFiProxyUtil.java    From WiFiProxySwitcher with Apache License 2.0 4 votes vote down vote up
/**
 * 低于 Android 5.0 系统
 */
private boolean setWiFiProxySettings4(String ip, int port) {
    // 获得 WifiConfiguration
    WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiConfiguration config = getCurrentWifiConfiguration(manager);
    if (null == config)
        return false;

    try {
        // 从 WifiConfiguration 中获得 linkProperties
        Object linkProperties = getField(config, "linkProperties");
        if (null == linkProperties)
            return false;

        // 获得 setHttpProxy 方法
        Class<?> proxyPropertiesClass = Class.forName("android.net.ProxyProperties");
        Class[] setHttpProxyParams = new Class[1];
        setHttpProxyParams[0] = proxyPropertiesClass;
        Class<?> lpClass = Class.forName("android.net.LinkProperties");
        Method setHttpProxy = lpClass.getDeclaredMethod("setHttpProxy", setHttpProxyParams);
        setHttpProxy.setAccessible(true);

        // 获得 ProxyProperties 构造方法
        Class[] proxyPropertiesCtorParamTypes = new Class[3];
        proxyPropertiesCtorParamTypes[0] = String.class;
        proxyPropertiesCtorParamTypes[1] = int.class;
        proxyPropertiesCtorParamTypes[2] = String.class;

        Constructor proxyPropertiesCtor = proxyPropertiesClass.getConstructor(proxyPropertiesCtorParamTypes);

        // 给构造方法创建参数
        Object[] proxyPropertiesCtorParams = new Object[3];
        proxyPropertiesCtorParams[0] = ip;
        proxyPropertiesCtorParams[1] = port;
        proxyPropertiesCtorParams[2] = null;

        // 创建 ProxyProperties 的对象
        Object proxySettings = proxyPropertiesCtor.newInstance(proxyPropertiesCtorParams);

        // 反射调用 linkProperties 的 setHttpProxy 方法, 参数为 ProxyProperties
        Object[] params = new Object[1];
        params[0] = proxySettings;
        setHttpProxy.invoke(linkProperties, params);

        setProxySettings("STATIC", config);

        // 保存设置
        manager.updateNetwork(config);
        manager.disconnect();
        manager.reconnect();

        ToastUtil.showToast(context, "保存Proxy设置成功");
        return true;
    } catch (Exception e) {
        ToastUtil.showToast(context, "保存Proxy设置失败");
        return false;
    }
}
 
Example 6
Source File: WiFiProxyUtil.java    From WiFiProxySwitcher with Apache License 2.0 4 votes vote down vote up
/**
 * 高于 Android 5.0 系统使用
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private boolean setWiFiProxySettings5(String ip, int port) {
    try {
        WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiConfiguration config = getCurrentWifiConfiguration(manager);
        Class proxySettings = Class.forName("android.net.IpConfiguration$ProxySettings");

        Class[] setProxyParams = new Class[2];
        setProxyParams[0] = proxySettings;
        setProxyParams[1] = ProxyInfo.class;

        Method setProxy = WifiConfiguration.class.getDeclaredMethod("setProxy", setProxyParams);
        setProxy.setAccessible(true);

        ProxyInfo proxyInfo = ProxyInfo.buildDirectProxy(ip, port);

        Object[] methodParams = new Object[2];
        methodParams[0] = Enum.valueOf(proxySettings, "STATIC");
        methodParams[1] = proxyInfo;

        setProxy.invoke(config, methodParams);

        manager.updateNetwork(config);

        String result = getCurrentWifiConfiguration(manager).toString();
        String key = "Proxy settings: ";
        int start = result.indexOf(key) + key.length();
        if (result.substring(start, start + 4).equals("NONE")) {
            throw new RuntimeException("Can't update the Network, you should have the right WifiConfiguration");
        }

        manager.disconnect();
        manager.reconnect();

        ToastUtil.showToast(context, "保存Proxy设置成功");
        return true;
    } catch (Exception e) {
        ToastUtil.showToast(context, "保存Proxy设置失败");
        return false;
    }
}
 
Example 7
Source File: WifiManagerModule.java    From react-native-wifi-manager with MIT License 4 votes vote down vote up
public void connectTo(ScanResult result, String password, String ssid) {
  //Make new configuration
  WifiConfiguration conf = new WifiConfiguration();
  conf.SSID = "\"" + ssid + "\"";
  String Capabilities = result.capabilities;
  if (Capabilities.contains("WPA2")) {
    conf.preSharedKey = "\"" + password + "\"";
  } else if (Capabilities.contains("WPA")) {
    conf.preSharedKey = "\"" + password + "\"";
  } else if (Capabilities.contains("WEP")) {
    conf.wepKeys[0] = "\"" + password + "\"";
    conf.wepTxKeyIndex = 0;
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
  } else {
    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
  }
  //Remove the existing configuration for this netwrok
  WifiManager mWifiManager = (WifiManager) getReactApplicationContext().getSystemService(Context.WIFI_SERVICE);
  List<WifiConfiguration> mWifiConfigList = mWifiManager.getConfiguredNetworks();
  String comparableSSID = ('"' + ssid + '"'); //Add quotes because wifiConfig.SSID has them
  for(WifiConfiguration wifiConfig : mWifiConfigList){
    if(wifiConfig.SSID.equals(comparableSSID)){
      int networkId = wifiConfig.networkId;
      mWifiManager.removeNetwork(networkId);
      mWifiManager.saveConfiguration();
    }
  }
  //Add configuration to Android wifi manager settings...
   WifiManager wifiManager = (WifiManager) getReactApplicationContext().getSystemService(Context.WIFI_SERVICE);
   mWifiManager.addNetwork(conf);
  //Enable it so that android can connect
  List < WifiConfiguration > list = mWifiManager.getConfiguredNetworks();
  for (WifiConfiguration i: list) {
    if (i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {
      wifiManager.disconnect();
      wifiManager.enableNetwork(i.networkId, true);
      wifiManager.reconnect();
      break;
    }
  }
}
 
Example 8
Source File: WifiBase.java    From android-wifi-activity with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    WifiManager wifi = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
    List<ScanResult> scanResultList = wifi.getScanResults();
    boolean found = false;
    String security = null;
    for (ScanResult scanResult : scanResultList) {
        if (scanResult.SSID.equals(getWifiSSID())) {
            security = getScanResultSecurity(scanResult);
            found = true;
            break; // found don't need continue
        }
    }
    if (!found) {
        // if no wifi network with the specified ssid is not found exit
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        new AlertDialog.Builder(context)
                .setCancelable(false)
                .setMessage(String.format(context.getString(R.string.wifi_not_found), getWifiSSID()))
                .setPositiveButton(context.getString(R.string.exit_app), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        getActivity().unregisterReceiver(ScanReceiver.this);
                        getActivity().finish();
                    }
                })
                .show();
    } else {
        // configure based on security
        final WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + getWifiSSID() + "\"";
        switch (security) {
            case WEP:
                conf.wepKeys[0] = "\"" + getWifiPass() + "\"";
                conf.wepTxKeyIndex = 0;
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                break;
            case PSK:
                conf.preSharedKey = "\"" + getWifiPass() + "\"";
                break;
            case OPEN:
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                break;
        }
        try {context.unregisterReceiver(connectionReceiver);} catch (Exception e) {} // do nothing

        connectionReceiver = new ConnectionReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        context.registerReceiver(connectionReceiver, intentFilter);
        int netId = wifi.addNetwork(conf);
        wifi.disconnect();
        wifi.enableNetwork(netId, true);
        wifi.reconnect();
        context.unregisterReceiver(this);
    }
}
 
Example 9
Source File: WifiBaseActivity.java    From android-wifi-activity with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
    List<ScanResult> scanResultList = wifi.getScanResults();
    boolean found = false;
    String security = null;
    for (ScanResult scanResult : scanResultList) {
        if (scanResult.SSID.equals(getWifiSSID())) {
            security = getScanResultSecurity(scanResult);
            found = true;
            break; // found don't need continue
        }
    }
    if (!found) {
        // if no wifi network with the specified ssid is not found exit
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        new AlertDialog.Builder(WifiBaseActivity.this)
                .setCancelable(false)
                .setMessage(String.format(getString(R.string.wifi_not_found), getWifiSSID()))
                .setPositiveButton(getString(R.string.exit_app), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        unregisterReceiver(ScanReceiver.this);
                        finish();
                    }
                })
                .show();
    } else {
        // configure based on security
        final WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + getWifiSSID() + "\"";
        switch (security) {
            case WEP:
                conf.wepKeys[0] = "\"" + getWifiPass() + "\"";
                conf.wepTxKeyIndex = 0;
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                break;
            case PSK:
                conf.preSharedKey = "\"" + getWifiPass() + "\"";
                break;
            case OPEN:
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                break;
        }
        connectionReceiver = new ConnectionReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        registerReceiver(connectionReceiver, intentFilter);
        List<WifiConfiguration> list = wifi.getConfiguredNetworks();
        for( WifiConfiguration i : list ) {
            wifi.removeNetwork(i.networkId);
            wifi.saveConfiguration();
        }
        int netId = wifi.addNetwork(conf);
        wifi.enableNetwork(netId, true);
        wifi.reconnect();
        unregisterReceiver(this);

    }
}
 
Example 10
Source File: WiFi.java    From WifiConnecter with Apache License 2.0 4 votes vote down vote up
/**
 * Connect to a configured network.
 * @param wifiManager
 * @param config
 * @param numOpenNetworksKept Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT
 * @return
 */
public static boolean connectToConfiguredNetwork( final WifiManager wifiMgr, WifiConfiguration config, boolean reassociate) {
	final String security = getWifiConfigurationSecurity(config);
	
	int oldPri = config.priority;
	// Make it the highest priority.
	int newPri = getMaxPriority(wifiMgr) + 1;
	if(newPri > MAX_PRIORITY) {
		newPri = shiftPriorityAndSave(wifiMgr);
		config = getWifiConfiguration(wifiMgr, config, security);
		if(config == null) {
			return false;
		}
	}
	
	// Set highest priority to this configured network
	config.priority = newPri;
	int networkId = wifiMgr.updateNetwork(config);
	if(networkId == -1) {
		return false;
	}
	
	// Do not disable others
	if(!wifiMgr.enableNetwork(networkId, false)) {
		config.priority = oldPri;
		return false;
	}
	
	if(!wifiMgr.saveConfiguration()) {
		config.priority = oldPri;
		return false;
	}
	
	// We have to retrieve the WifiConfiguration after save.
	config = getWifiConfiguration(wifiMgr, config, security);
	if(config == null) {
		return false;
	}
	
	// Disable others, but do not save.
	// Just to force the WifiManager to connect to it.
	if(!wifiMgr.enableNetwork(config.networkId, true)) {
		return false;
	}
	
	final boolean connect = reassociate ? wifiMgr.reassociate() : wifiMgr.reconnect();
	if(!connect) {
		return false;
	}
	
	return true;
}
 
Example 11
Source File: WifiHelper.java    From android-wear-gopro-remote with Apache License 2.0 4 votes vote down vote up
public static boolean connectToWifi(Context context, int networkId) {

        if(networkId <= -3) return false; // Do nothing

        final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager == null) {
            Logger.error(TAG, "No WiFi manager");
            return false;
        }

        WifiInfo info = wifiManager.getConnectionInfo();
        if(info != null && info.getNetworkId() == networkId) {
            return true;
        }

        if(networkId == -2) { // Disable
            return wifiManager.setWifiEnabled(false);
        }

        if(!wifiManager.isWifiEnabled()) {
            return false;
        }

        if (!wifiManager.disconnect()) {
            Logger.error(TAG, "WiFi disconnect failed");
            return false;
        }

        if(networkId == -1) { // Disconnect
            return true;
        }

        if (!wifiManager.enableNetwork(networkId, true)) {
            Logger.error(TAG, "Could not enable WiFi.");
            return false;
        }

        if (!wifiManager.reconnect()) {
            Logger.error(TAG, "WiFi reconnect failed");
            return false;
        }

        return true;
    }
 
Example 12
Source File: WifiHelper.java    From android-wear-gopro-remote with Apache License 2.0 4 votes vote down vote up
public static boolean connectToWifi(Context context, final String ssid, String password) {

        int networkId = -1;
        int c;

        final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager == null) {
            Logger.error(TAG, "No WiFi manager");
            return false;
        }

        List<WifiConfiguration> list;

        if (wifiManager.isWifiEnabled()) {
            list = wifiManager.getConfiguredNetworks();
        } else {
            if (!wifiManager.setWifiEnabled(true)) {
                Logger.error(TAG, "Enable WiFi failed");
                return false;
            }
            c = 0;
            do {
                Utils.sleep(500);
                list = wifiManager.getConfiguredNetworks();
            } while (list == null && ++c < 10);
        }

        if (list == null) {
            Logger.error(TAG, "Could not get WiFi network list");
            return false;
        }

        for (WifiConfiguration i : list) {
            if (i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {
                networkId = i.networkId;
                break;
            }
        }

        WifiInfo info;
        if (networkId < 0) {
            WifiConfiguration conf = new WifiConfiguration();
            conf.SSID = "\"" + ssid + "\"";
            conf.preSharedKey = "\"" + password + "\"";
            networkId = wifiManager.addNetwork(conf);
            if (networkId < 0) {
                Logger.error(TAG, "New WiFi config failed");
                return false;
            }
        } else {
            info = wifiManager.getConnectionInfo();
            if (info != null) {
                if (info.getNetworkId() == networkId) {
                    if(Logger.DEBUG) Logger.debug(TAG, "Already connected to " + ssid);
                    return true;
                }
            }
        }

        if (!wifiManager.disconnect()) {
            Logger.error(TAG, "WiFi disconnect failed");
            return false;
        }

        if (!wifiManager.enableNetwork(networkId, true)) {
            Logger.error(TAG, "Could not enable WiFi.");
            return false;
        }

        if (!wifiManager.reconnect()) {
            Logger.error(TAG, "WiFi reconnect failed");
            return false;
        }

        c = 0;
        do {
            info = wifiManager.getConnectionInfo();
            if (info != null && info.getNetworkId() == networkId &&
                    info.getSupplicantState() == SupplicantState. COMPLETED &&  info.getIpAddress() != 0) {
                if(Logger.DEBUG) Logger.debug(TAG, "Successfully connected to %s %d", ssid, info.getIpAddress());
                return true;
            }
            Utils.sleep(500);
        } while (++c < 30);

        Logger.error(TAG, "Failed to connect to " + ssid);
        return false;
    }