I have checked in Stack Overflow question API for configuring static IP addresses in an Android application.
It works until Android 2.3. However, there is no luck on a higher API level. For example,
I put the setting
android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_USE_STATIC_IP, "1");
android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_IP, "192.168.0.100");
android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_NETMASK, "255.255.255.0");
android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_DNS1, "192.168.0.254");
android.provider.Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_GATEWAY, "192.168.0.254");
But I go back to check by:
Setting --> Wi-Fi --> Long Press Access Point SSID --> Modify Network --> check Show advanced options
The IP Settings field is still stated DHCP but not Static.
It is true that I can use android.provider.Settings.System.getString() to get back what I set. It prove that the setting is saved somewhere but the system just ignore it.
The system uses the setting other than android.provider.Settings.System on Android 3.x and 4.x as the setting is set per Access Point SSID. Can I modify the setting on one SSID just like how it works on Android 2.3?
I realise that there is no API on 3.x or 4.x for those setting per SSID. Therefore, I checked out the source code and found out that the configuration of each SSID is stored in
android.net.wifi.WifiConfigurationwhich is gotten fromandroid.net.wifi.WifiManager.In the below code,
IpAssignmentis an Enum, eitherSTAIC,DHCPorNONE.And
linkPropertiesis the object store IP address, gateway, DNS, etc…linkAddressis IP address and its netmask as prefixLength (how many bit 1 in netmask).mRoutesisArrayListofRouteInfothat can indicate gateway.mDnsesisArrayListofInetAddressfor DNS.Firstly, get the current configuration using
WifiConfigurationSSIDAs the
IpAssignmentandlinkPropertiesare hidden, the object can be gotten from reflection.The following method can set the declared IP address setting on SSID WifiConfiguration:
After that, I can set setting and update
WifiConfigurationfor this SSID.Edit:
Sorry for I don’t check for Android 3.x device that have silmilar UI with Android 4.x.
In Android 3.x, the gateway is storted in
mGatewaysoflinkProperties.mGatewaysisArraylistof typeInetAddress. Therefore, following should work in Android 3.x.Edit2: The methods
setIpAddress,setGateway,setDNSshould be inputted asInetAddresstype.