Android下用代码设置静态IP地址的方法(完美支持Android2.X,Android3.X,Android4.X)

有一个项目,要控制设备wifi连接,而且要使用静态ip,上网查找了下,基本都是Android2.X下面的方法,即使用Settings进行设置,但是这种设置方法对于Android3.X以上设备是无效的,通过研究在Android手机上手动设置静态ip,我们可以发现:

     1、Android2.X系统下面,静态IP地址是一个全局设置,即设置好之后会对你以后连接的所有热点生效,都会使用你设置的IP地址

     2、Android3.X以上系统,设置静态ip是针对每一个点连接的配置进行的,在热点1上的设置不会影响热点2

 

     ok,基本明白了,Android2.X使用Settings进行设置,是一个全局设定,而之后的系统做了修改,更改了设置模式,将静态ip设置与每一个热点挂钩,那会不会是在热点的配置类里面实现的呢,为了验证,我们查看了Android4.0的sdk源码,分析完WifiConfiguration.java后,就明白了,里面有“ipAssignment”,“linkProperties”,"mRoutes"(3.x系统为“mGateways”)等多个新增的hidden项,看来只能通过反射的方法调用了,呵呵,下面上代码:

 

[java] view plaincopy
01.//******************************************************************************/ 
02.    //以下代码为android3.0及以上系统设置静态ip地址的方法 

 


[java] view plaincopy
01.  

 


[java] view plaincopy
01./*设置ip地址类型 assign:STATIC/DHCP 静态/动态*/ 

 


[java] view plaincopy
01.    private static void setIpAssignment(String assign, WifiConfiguration wifiConf) 
02.        throws SecurityException, IllegalArgumentException, 
03.        NoSuchFieldException, IllegalAccessException { 
04.    setEnumField(wifiConf, assign, "ipAssignment"); 
05.} 
06. 
07.@SuppressWarnings("unchecked") 

 


[java] view plaincopy
01./*设置ip地址*/ 

 


[java] view plaincopy
01.    private static void setIpAddress(InetAddress addr, int prefixLength, 
02.            WifiConfiguration wifiConf) throws SecurityException, 
03.            IllegalArgumentException, NoSuchFieldException, 
04.            IllegalAccessException, NoSuchMethodException, 
05.            ClassNotFoundException, InstantiationException, 
06.            InvocationTargetException { 
07.        Object linkProperties = getField(wifiConf, "linkProperties"); 
08.        if (linkProperties == null) 
09.            return; 
10.        Class<?> laClass = Class.forName("android.net.LinkAddress"); 
11.        Constructor<?> laConstructor = laClass.getConstructor(new Class[] { 
12.                InetAddress.class, int.class }); 
13.        Object linkAddress = laConstructor.newInstance(addr, prefixLength); 
14. 
15.        ArrayList<Object> mLinkAddresses = (ArrayList<Object>) getDeclaredField( 
16.                linkProperties, "mLinkAddresses"); 
17.        mLinkAddresses.clear(); 
18.        mLinkAddresses.add(linkAddress); 
19.    } 
20. 
21.        @SuppressWarnings("unchecked")<pre class="java" name="code">        /*设置网关*/ 
22.    private static void setGateway(InetAddress gateway, 
23.            WifiConfiguration wifiConf) throws SecurityException, 
24.            IllegalArgumentException, NoSuchFieldException, 
25.            IllegalAccessException, ClassNotFoundException, 
26.            NoSuchMethodException, InstantiationException, 
27.            InvocationTargetException { 
28.        Object linkProperties = getField(wifiConf, "linkProperties"); 
29.        if (linkProperties == null) 
30.            return; 
31. 
32.        if (android.os.Build.VERSION.SDK_INT >= 14) { // android4.x版本 
33.            Class<?> routeInfoClass = Class.forName("android.net.RouteInfo"); 
34.            Constructor<?> routeInfoConstructor = routeInfoClass 
35.                    .getConstructor(new Class[] { InetAddress.class }); 
36.            Object routeInfo = routeInfoConstructor.newInstance(gateway); 
37. 
38.            ArrayList<Object> mRoutes = (ArrayList<Object>) getDeclaredField( 
39.                    linkProperties, "mRoutes"); 
40.            mRoutes.clear(); 
41.            mRoutes.add(routeInfo); 
42.        } else { // android3.x版本 
43.            ArrayList<InetAddress> mGateways = (ArrayList<InetAddress>) getDeclaredField( 
44.                    linkProperties, "mGateways"); 
45.            mGateways.clear(); 
46.            mGateways.add(gateway); 
47.        } 
48. 
49.    } 
50.     
51. 
52.        @SuppressWarnings("unchecked")<pre class="java" name="code">        /*设置域名解析服务器*/ 
53.</pre> private static void setDNS(InetAddress dns, WifiConfiguration wifiConf)throws SecurityException, IllegalArgumentException,NoSuchFieldException, IllegalAccessException 
54. {Object linkProperties = getField(wifiConf, "linkProperties");if (linkProperties == null)return;ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(linkProperties, "mDnses");mDnses.clear(); // 清除原有DNS设置(如果只想增加,不想清除,词句可省略)mDnses.add(dns); 
55. //增加新的DNS}private static Object getField(Object obj, String name)throws SecurityException, NoSuchFieldException,IllegalArgumentException, IllegalAccessException {Field f = obj.getClass().getField(name);Object out = f.get(obj);return out;}private static Object 
56. getDeclaredField(Object obj, String name)throws SecurityException, NoSuchFieldException,IllegalArgumentException, IllegalAccessException {Field f = obj.getClass().getDeclaredField(name);f.setAccessible(true);Object out = f.get(obj);return out;}@SuppressWarnings({ 
57. "unchecked", "rawtypes" })private static void setEnumField(Object obj, String value, String name)throws SecurityException, NoSuchFieldException,IllegalArgumentException, IllegalAccessException {Field f = obj.getClass().getField(name);f.set(obj, Enum.valueOf((Class<Enum>) 
58. f.getType(), value));} //***以上是android3.x以上设置静态ip地址的方法********************************************************************************* 
59.<pre></pre> 
60.<pre></pre> 
61.<p><br> 
62. </p> 
63.<p>下面是调用方法:</p> 
64.<pre class="java" name="code"><p> </p><pre class="java" name="code">   private void setIpWithTfiStaticIp() { 
65. 
66.        WifiConfiguration wifiConfig; 
67. 
68.        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
69.        WifiInfo connectionInfo = wifiManager.getConnectionInfo(); 
70.        List<WifiConfiguration> configuredNetworks = wifiManager 
71.                .getConfiguredNetworks(); 
72.        for (WifiConfiguration conf : configuredNetworks) { 
73.            if (wifiConf.networkId == connectionInfo.getNetworkId()) { 
74.                WifiConf = conf; 
75.                break; 
76.            } 
77.        } 
78. 
79.        if (android.os.Build.VERSION.SDK_INT < 11) { // 如果是android2.x版本的话 
80. 
81.            ContentResolver ctRes = context.getContentResolver(); 
82.            Settings.System 
83.                    .putInt(ctRes, Settings.System.WIFI_USE_STATIC_IP, 1); 
84.            Settings.System.putString(ctRes, Settings.System.WIFI_STATIC_IP, 
85.                    "192.168.0.202"); 
86.            Settings.System.putString(ctRes, 
87.                    Settings.System.WIFI_STATIC_NETMASK, "255.255.255.0"); 
88.            Settings.System.putString(ctRes, 
89.                    Settings.System.WIFI_STATIC_GATEWAY, "192.168.0.1"); 
90.            Settings.System.putString(ctRes, Settings.System.WIFI_STATIC_DNS1, 
91.                    "192.168.0.1"); 
92.            Settings.System.putString(ctRes, Settings.System.WIFI_STATIC_DNS2, 
93.                    "61.134.1.9"); 
94. 
95.        } else { // 如果是android3.x版本及以上的话 
96.            try { 
97.                setIpAssignment("STATIC", wifiConfig); 
98.                setIpAddress(InetAddress.getByName("192.168.0.202"), 24, 
99.                        wifiConfig); 
100.                setGateway(InetAddress.getByName("192.168.0.1"), wifiConfig); 
101.                setDNS(InetAddress.getByName("192.168.0.1"), wifiConfig); 
102.                wifiManager.updateNetwork(wifiConfig); // apply the setting 
103.                System.out.println("静态ip设置成功!"); 
104.            } catch (Exception e) { 
105.                e.printStackTrace(); 
106.                System.out.println("静态ip设置失败!"); 
107.            } 
108.        } 
109. 
110.    }</pre>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值