How To Change Wifi Advanced Option From Code That Chrome Lost Access To Internet
this is my situation : I have an android device that is not root. this device connected to a wifi modem that has internet access, so the device has internet access and chrome can
Solution 1:
According to linked code which i have answered there is hard-coded network id so all the efforts of ip and dns setting wont get applied .
Below is my complete modified code of proxy setting : [Note : please do check hard-coded things and change it accordingly]
publicclassMainActivityextendsActionBarActivity {
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newaynctask().execute();
}
publicclassaynctaskextendsAsyncTask<Void, Void, Void> {
@Overrideprotected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
connectToAP("MyWifi", "qwer!@#$");
WifiConfigurationwifiConf=null;
WifiManagerwifiManager= (WifiManager) getSystemService(MainActivity.WIFI_SERVICE);
WifiInfoconnectionInfo= wifiManager.getConnectionInfo();
List<WifiConfiguration> configuredNetworks = wifiManager
.getConfiguredNetworks();
for (WifiConfiguration conf : configuredNetworks) {
Log.d(TAG, "conf.networkId == 1" + (conf.networkId == 9));
Log.d(TAG, " conf.networkId == " + conf.networkId);
Log.d(TAG, " conf.bbid == " + conf.BSSID);
Log.d(TAG, " conf.ssid == " + conf.SSID);
StringBACKSLASH="\"";
if (conf.SSID.equals(BACKSLASH + "MyWifi" + BACKSLASH)) {
// if (conf.SSID.equals("12345")) {
wifiConf = conf;
setWifiProxySettings(wifiConf);
try {
setIpAssignment("STATIC", wifiConf); // or "DHCP" for// dynamic setting
setIpAddress(InetAddress.getByName("155.128.0.100"),
24, wifiConf);
setGateway(InetAddress.getByName("8.2.4.2"), wifiConf);
// setDNS(InetAddress.getByName("4.3.4.3"), wifiConf);
wifiManager.updateNetwork(wifiConf); // apply the// setting
wifiManager.saveConfiguration(); // Save it
wifiManager.disconnect();
wifiManager.reconnect();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
returnnull;
}
}
publicstaticvoidsetIpAssignment(String assign, WifiConfiguration wifiConf)throws SecurityException, IllegalArgumentException,
NoSuchFieldException, IllegalAccessException {
setEnumField(wifiConf, assign, "ipAssignment");
}
publicstaticvoidsetEnumField(Object obj, String value, String name)throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Fieldf= obj.getClass().getField(name);
f.set(obj, Enum.valueOf((Class<Enum>) f.getType(), value));
}
publicstaticvoidsetIpAddress(InetAddress addr, int prefixLength,
WifiConfiguration wifiConf)throws SecurityException,
IllegalArgumentException, NoSuchFieldException,
IllegalAccessException, NoSuchMethodException,
ClassNotFoundException, InstantiationException,
InvocationTargetException {
ObjectlinkProperties= getField(wifiConf, "linkProperties");
if (linkProperties == null)
return;
ClasslaClass= Class.forName("android.net.LinkAddress");
ConstructorlaConstructor= laClass.getConstructor(newClass[] {
InetAddress.class, int.class });
ObjectlinkAddress= laConstructor.newInstance(addr, prefixLength);
ArrayListmLinkAddresses= (ArrayList) getDeclaredField(linkProperties,
"mLinkAddresses");
mLinkAddresses.clear();
mLinkAddresses.add(linkAddress);
}
publicstaticvoidsetGateway(InetAddress gateway,
WifiConfiguration wifiConf)throws SecurityException,
IllegalArgumentException, NoSuchFieldException,
IllegalAccessException, ClassNotFoundException,
NoSuchMethodException, InstantiationException,
InvocationTargetException {
ObjectlinkProperties= getField(wifiConf, "linkProperties");
if (linkProperties == null)
return;
ClassrouteInfoClass= Class.forName("android.net.RouteInfo");
ConstructorrouteInfoConstructor= routeInfoClass
.getConstructor(newClass[] { InetAddress.class });
ObjectrouteInfo= routeInfoConstructor.newInstance(gateway);
ArrayListmRoutes= (ArrayList) getDeclaredField(linkProperties,
"mRoutes");
mRoutes.clear();
mRoutes.add(routeInfo);
}
publicstaticvoidsetDNS(InetAddress dns, WifiConfiguration wifiConf)throws SecurityException, IllegalArgumentException,
NoSuchFieldException, IllegalAccessException {
ObjectlinkProperties= getField(wifiConf, "linkProperties");
if (linkProperties == null)
return;
ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(
linkProperties, "mDnses");
mDnses.clear(); // or add a new dns address , here I just want to// replace DNS1
mDnses.add(dns);
}
publicstatic Object getField(Object obj, String name)throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Fieldf= obj.getClass().getField(name);
Objectout= f.get(obj);
return out;
}
publicstatic Object getDeclaredField(Object obj, String name)throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Fieldf= obj.getClass().getDeclaredField(name);
f.setAccessible(true);
Objectout= f.get(obj);
return out;
}
@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
returntrue;
}
@OverridepublicbooleanonOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.intid= item.getItemId();
if (id == R.id.action_settings) {
returntrue;
}
returnsuper.onOptionsItemSelected(item);
}
StringTAG="wifi";
WifiManager wifiManager;
publicvoidconnectToAP(String ssid, String passkey) {
StringBACKSLASH="\"";
StringNETWROK_SECURITY_WEP="WEP";
StringNETWROK_SECURITY_NONE="NONE";
StringNETWROK_SECURITY_WPA="WPA";
StringNETWROK_SECURITY_WPA2="WPA2";
StringNETWROK_SECURITY_WPA_WPA2="WPA/WPA2 PSK";
StringNETWROK_ADDITIONAL_SECURITY_TKIP="TKIP";
StringNETWROK_ADDITIONAL_SECURITY_AES="AES";
StringNETWROK_ADDITIONAL_SECURITY_WEP="WEP";
StringNETWROK_ADDITIONAL_SECURITY_NONE="NONE";
intFAILED_TO_ADD_NETWORK= -1;
Log.d(TAG, "Inside addWifiConfig...");
WifiConfigurationconf=newWifiConfiguration();
StringwifiName= ssid;
conf.SSID = BACKSLASH + wifiName + BACKSLASH;
StringsecurityType= NETWROK_SECURITY_WPA_WPA2;
Log.d(TAG, "Security Type :: " + securityType);
if (NETWROK_SECURITY_WEP.equalsIgnoreCase(securityType)) {
conf.wepKeys[0] = passkey;
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
} elseif (NETWROK_SECURITY_NONE.equalsIgnoreCase(securityType)) {
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
} elseif (NETWROK_SECURITY_WPA.equalsIgnoreCase(securityType)
|| NETWROK_SECURITY_WPA2.equalsIgnoreCase(securityType)
|| NETWROK_SECURITY_WPA_WPA2.equalsIgnoreCase(securityType)) {
conf.preSharedKey = BACKSLASH + passkey + BACKSLASH;
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.status = WifiConfiguration.Status.ENABLED;
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
}
// TODO need to cheak if security detail is neededStringwlanAdditionalSecurity="";
if (NETWROK_ADDITIONAL_SECURITY_TKIP
.equalsIgnoreCase(wlanAdditionalSecurity)) {
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
} elseif (NETWROK_ADDITIONAL_SECURITY_AES
.equalsIgnoreCase(wlanAdditionalSecurity)) {
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
} elseif (NETWROK_ADDITIONAL_SECURITY_WEP
.equalsIgnoreCase(wlanAdditionalSecurity)) {
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
} elseif (NETWROK_ADDITIONAL_SECURITY_NONE
.equalsIgnoreCase(wlanAdditionalSecurity)) {
conf.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.NONE);
}
WifiManagerwifiManager= (WifiManager) MainActivity.this
.getSystemService(Context.WIFI_SERVICE);
// if (proxyProperties != null && proxyProperties.IsEnabled()) {// WifiManagerUtils.setWifiProxySettings(wifiPolicy, conf);// }intres= wifiManager.addNetwork(conf);
// TODO Make sure why disconnect and connect required here.// In current this is causing problem while sending job status to// server. Agent fails to send status because of network disconnect.
wifiManager.disconnect();
wifiManager.reconnect();
if (true) {
wifiManager.enableNetwork(res, true);
wifiManager.saveConfiguration();
wifiManager.setWifiEnabled(true);
}
if (res == FAILED_TO_ADD_NETWORK) {
// return false;
} else {
// return true;
}
}
public String getScanResultSecurity(ScanResult scanResult) {
Log.i(TAG, "* getScanResultSecurity");
finalStringcap= scanResult.capabilities;
final String[] securityModes = { "WEP", "PSK", "EAP" };
for (inti= securityModes.length - 1; i >= 0; i--) {
if (cap.contains(securityModes[i])) {
return securityModes[i];
}
}
return"OPEN";
}
publicstaticvoidsetProxySettings(String assign,
WifiConfiguration wifiConf)throws SecurityException,
IllegalArgumentException, NoSuchFieldException,
IllegalAccessException {
setEnumField(wifiConf, assign, "proxySettings");
}
WifiConfiguration GetCurrentWifiConfiguration(WifiManager manager) {
if (!manager.isWifiEnabled())
returnnull;
List<WifiConfiguration> configurationList = manager
.getConfiguredNetworks();
WifiConfigurationconfiguration=null;
intcur= manager.getConnectionInfo().getNetworkId();
for (inti=0; i < configurationList.size(); ++i) {
WifiConfigurationwifiConfiguration= configurationList.get(i);
if (wifiConfiguration.networkId == cur)
configuration = wifiConfiguration;
}
return configuration;
}
voidsetWifiProxySettings(WifiConfiguration config) {
// get the current wifi configuration// WifiManager manager = (WifiManager)// getSystemService(Context.WIFI_SERVICE);// WifiConfiguration config = GetCurrentWifiConfiguration(manager);if (null == config)
return;
try {
// get the link properties from the wifi configurationObjectlinkProperties= getField(config, "linkProperties");
if (null == linkProperties)
return;
// get the setHttpProxy method for LinkPropertiesClassproxyPropertiesClass= Class
.forName("android.net.ProxyProperties");
Class[] setHttpProxyParams = newClass[1];
setHttpProxyParams[0] = proxyPropertiesClass;
ClasslpClass= Class.forName("android.net.LinkProperties");
MethodsetHttpProxy= lpClass.getDeclaredMethod("setHttpProxy",
setHttpProxyParams);
setHttpProxy.setAccessible(true);
// get ProxyProperties constructor
Class[] proxyPropertiesCtorParamTypes = newClass[3];
proxyPropertiesCtorParamTypes[0] = String.class;
proxyPropertiesCtorParamTypes[1] = int.class;
proxyPropertiesCtorParamTypes[2] = String.class;
ConstructorproxyPropertiesCtor= proxyPropertiesClass
.getConstructor(proxyPropertiesCtorParamTypes);
// create the parameters for the constructor
Object[] proxyPropertiesCtorParams = newObject[3];
proxyPropertiesCtorParams[0] = "127.0.0.1";
proxyPropertiesCtorParams[1] = 8118;
proxyPropertiesCtorParams[2] = "example.com";
// create a new object using the paramsObjectproxySettings= proxyPropertiesCtor
.newInstance(proxyPropertiesCtorParams);
// pass the new object to setHttpProxy
Object[] params = newObject[1];
params[0] = proxySettings;
setHttpProxy.invoke(linkProperties, params);
setProxySettings("STATIC", config);
// // save the settings// manager.updateNetwork(config);// manager.disconnect();// manager.reconnect();
} catch (Exception e) {
}
}
voidunsetWifiProxySettings() {
WifiManagermanager= (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiConfigurationconfig= GetCurrentWifiConfiguration(manager);
if (null == config)
return;
try {
// get the link properties from the wifi configurationObjectlinkProperties= getField(config, "linkProperties");
if (null == linkProperties)
return;
// get the setHttpProxy method for LinkPropertiesClassproxyPropertiesClass= Class
.forName("android.net.ProxyProperties");
Class[] setHttpProxyParams = newClass[1];
setHttpProxyParams[0] = proxyPropertiesClass;
ClasslpClass= Class.forName("android.net.LinkProperties");
MethodsetHttpProxy= lpClass.getDeclaredMethod("setHttpProxy",
setHttpProxyParams);
setHttpProxy.setAccessible(true);
// pass null as the proxy
Object[] params = newObject[1];
params[0] = null;
setHttpProxy.invoke(linkProperties, params);
setProxySettings("NONE", config);
// save the config
manager.updateNetwork(config);
manager.disconnect();
manager.reconnect();
} catch (Exception e) {
}
}
}
There are some extra code i have added apart from my previous answer so basically when this code runs successfully and when u navigate via browser anywhere this is output :
EDIT : API FOR LOLLIPOP [the above api for proxy and ip wont work in latest Andriod L ]
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
// Implementation for Proxy setting for LOLLIPOPtry {
URL proxyUrl = newURL(
addNetworkProxyProperties.getHttpProxyUri());
String host = proxyUrl.getHost();
int portStr = proxyUrl.getPort();
String exclusionList = addNetworkProxyProperties
.getExceptions();
Constructor<ProxyInfo> constructor = ProxyInfo.class
.getConstructor(new Class[] { String.class, int.class,
String.class });
ProxyInfo mHttpProxy = constructor.newInstance(new Object[] {
host, portStr, exclusionList });
Class ipConfigClass = Class
.forName("android.net.IpConfiguration");
Object ipConfigObject = ipConfigClass.newInstance();
Method setHttpProxy = ipConfigClass.getDeclaredMethod(
"setHttpProxy", ProxyInfo.class);
setHttpProxy.setAccessible(true);
setHttpProxy.invoke(ipConfigObject, mHttpProxy);
Method getHttpProxySettings = ipConfigClass
.getDeclaredMethod("getProxySettings");
getHttpProxySettings.setAccessible(true);
Method setProxy = config.getClass().getDeclaredMethod(
"setProxy",
getHttpProxySettings.invoke(ipConfigObject).getClass(),
ProxyInfo.class);
setProxy.setAccessible(true);
setEnumField(ipConfigObject, "STATIC", "proxySettings");
setProxy.invoke(config,
getHttpProxySettings.invoke(ipConfigObject), mHttpProxy);
} catch (Exception e) {
/*
* Excepted exceptions may be SecurityException,
* IllegalArgumentException, IllegalAccessException,
* InvocationTargetException, NoSuchMethodException,
* InstantiationException, ClassNotFoundException,
* NoSuchFieldException, MalformedURLException
*/
e.printStackTrace();
}
}
NOTE in LOLLIPOP do chnage below statement for connecting the wifi :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
conf.SSID = wifiName;
} else {
conf.SSID = Constants.BACKSLASH + wifiName + Constants.BACKSLASH;
}
Post a Comment for "How To Change Wifi Advanced Option From Code That Chrome Lost Access To Internet"