android修改静态ip(支持3.x,4.x,5.x)

来源:互联网 发布:网络直播的定义 编辑:程序博客网 时间:2024/04/28 16:12

//Android 3.x,4.x修改静态ip


[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. package com.example.iptest;  
  2.   
  3. import java.lang.reflect.Constructor;  
  4. import java.lang.reflect.Field;  
  5. import java.lang.reflect.InvocationTargetException;  
  6. import java.net.InetAddress;  
  7. import java.util.ArrayList;  
  8. import java.util.List;  
  9.   
  10. import android.app.Activity;  
  11. import android.content.Context;  
  12. import android.net.wifi.WifiConfiguration;  
  13. import android.net.wifi.WifiInfo;  
  14. import android.net.wifi.WifiManager;  
  15. import android.os.Build;  
  16. import android.os.Bundle;  
  17. import android.widget.Toast;  
  18.   
  19. public class MainActivity extends Activity {  
  20.   
  21.       
  22.     @Override  
  23.     protected void onCreate(Bundle savedInstanceState) {  
  24.         super.onCreate(savedInstanceState);  
  25.         setContentView(R.layout.activity_main);  
  26.         System.out.println(android.os.Build.VERSION.SDK_INT);  
  27.         setIpWithTfiStaticIp();  
  28.     }  
  29.   
  30. /*  设置ip地址类型 assign: STATIC/DHCP 静态/动态 
  31. */  private static void setIpAssignment(String assign, WifiConfiguration wifiConf) throws SecurityException,IllegalArgumentException,NoSuchFieldException,IllegalAccessException, InvocationTargetException, NoSuchMethodException  
  32.     {  
  33.           
  34.         if (Build.VERSION.SDK_INT >= 21) {  
  35.             Object ipConfiguration = wifiConf.getClass()  
  36.                     .getMethod(”getIpConfiguration”).invoke(wifiConf);  
  37.             setEnumField(ipConfiguration, assign, ”ipAssignment”);  
  38.         }  
  39.     }  
  40. //  设置ip地址  
  41.     private static void setIpAddress(InetAddress addr,int prefixLength,WifiConfiguration wificonf) throws SecurityException,IllegalArgumentException,NoSuchFieldException,IllegalAccessException,NoSuchMethodException,ClassNotFoundException,InstantiationException,InvocationTargetException  
  42.     {  
  43.         Object linkProperties=getField(wificonf,”linkProperties”);  
  44.         if(linkProperties==null)  
  45.         {  
  46.             return;  
  47.         }  
  48.             Class<?> laClass=Class.forName(”android.net.LinkAddress”);  
  49.             Constructor<?> laConstructor=laClass.getConstructor(new Class[]{  
  50.                     InetAddress.class,int.class  
  51.             });  
  52.          Object linkAddress=laConstructor.newInstance(addr,prefixLength);  
  53.          ArrayList<Object> mLinkAddresses=(ArrayList<Object>)getDeclaredField(linkProperties,”mLinkAddresses”);  
  54.          mLinkAddresses.clear();  
  55.          mLinkAddresses.add(linkAddress);  
  56.           
  57.     }  
  58.     @SuppressWarnings(“unchecked”)  
  59. //  设置网关  
  60.     private static void setGateway(InetAddress gateway, WifiConfiguration wifiConf) throws SecurityException,IllegalArgumentException,NoSuchFieldException,IllegalAccessException,ClassNotFoundException,NoSuchMethodException,InstantiationException,InvocationTargetException  
  61.     {  
  62.         Object linkProperties=getField(wifiConf,”linkProperties”);  
  63.         if(linkProperties==null)  
  64.         {  
  65.             return;  
  66.         }  
  67.         if(android.os.Build.VERSION.SDK_INT>=14)  
  68.         {  
  69.             //android4.x版本  
  70.             Class<?> routeInfoClass=Class.forName(”android.net.RouteInfo”);  
  71.             Constructor<?> routeInfoConstructor=routeInfoClass.getConstructor(new Class[]{InetAddress.class});  
  72.             Object routeInfo=routeInfoConstructor.newInstance(gateway);  
  73.             ArrayList<Object> mRoutes=(ArrayList<Object>)getDeclaredField(linkProperties,”mRoutes”);  
  74.             mRoutes.clear();  
  75.             mRoutes.add(routeInfo);  
  76.         }  
  77.         /*else 
  78.         { 
  79.             //android 3.x版本 
  80.             ArrayList<InetAddress> mGateways=(ArrayList<InetAddress>)getDeclaredField(linkProperties,”mGateways”); 
  81.             mGateways.clear(); 
  82.             mGateways.add(gateway); 
  83.         }*/  
  84.     }  
  85.     @SuppressWarnings(“unchecked”)  
  86.     //设置域名解析服务器  
  87.     private static void setDNS(InetAddress dns,WifiConfiguration wifiConf) throws SecurityException,IllegalArgumentException,NoSuchFieldException,IllegalAccessException{  
  88.         Object linkProperties=getField(wifiConf,”linkProperties”);  
  89.         if(linkProperties==null)  
  90.         {  
  91.             return;  
  92.         }  
  93.         ArrayList<InetAddress> mDnses=(ArrayList<InetAddress>)getDeclaredField(linkProperties,”mDnses”);  
  94.         //清除原有Dns设置(如果只想增加,不想清除,词句可省略)  
  95.         mDnses.clear();  
  96.         //增加新的DNS  
  97.         mDnses.add(dns);  
  98.     }  
  99.     private static Object getField(Object obj,String name) throws SecurityException,NoSuchFieldException,IllegalArgumentException,IllegalAccessException  
  100.     {  
  101.           
  102.         Field f=obj.getClass().getField(name);  
  103.         Object out=f.get(obj);  
  104.         return out;  
  105.     }  
  106.     private static Object getDeclaredField(Object obj,String name) throws SecurityException,NoSuchFieldException,IllegalArgumentException,IllegalAccessException  
  107.     {  
  108.         Field f=obj.getClass().getDeclaredField(name);  
  109.         f.setAccessible(true);  
  110.         Object out=f.get(obj);  
  111.         return out;  
  112.     }  
  113.     @SuppressWarnings({“unchecked”,“rawtypes”})  
  114.     private static void setEnumField(Object obj,String value,String name) throws SecurityException,NoSuchFieldException,IllegalArgumentException,IllegalAccessException  
  115.     {  
  116.       
  117.         Field f=obj.getClass().getField(name);  
  118.         f.set(obj, Enum.valueOf((Class<Enum>)f.getType(),value));  
  119.     }  
  120.     //以上是android3.x以上设置静态ip地址的方法  
  121.       
  122.     //下面是调用方法  
  123.     private void setIpWithTfiStaticIp()  
  124.     {  
  125.         WifiConfiguration wifiConfig=null;  
  126.         WifiManager wifiManager=(WifiManager)getSystemService(Context.WIFI_SERVICE);  
  127.         WifiInfo connectionInfo=wifiManager.getConnectionInfo();  
  128.         List<WifiConfiguration> configuredNetworks=wifiManager.getConfiguredNetworks();  
  129.         for (WifiConfiguration conf : configuredNetworks) {  
  130.             if (conf.networkId==connectionInfo.getNetworkId()) {  
  131.                 wifiConfig=conf;  
  132.                 break;  
  133.             }  
  134.         }  
  135.         /*if(android.os.Build.VERSION.SDK_INT<11) 
  136.         { 
  137.             //如果是android2.x版本的话 
  138.             ContentResolver ctRes=this.getContentResolver(); 
  139.             Settings.System.putInt(ctRes, Settings.System.WIFI_USE_STATIC_IP,1); 
  140.             Settings.System.putString(ctRes, Settings.System.WIFI_STATIC_IP,”192.168.0.202”); 
  141.             Settings.System.putString(ctRes, Settings.System.WIFI_STATIC_NETMASK,”255.255.255.0”); 
  142.             Settings.System.putString(ctRes, Settings.System.WIFI_STATIC_GATEWAY,”192.168.0.1”); 
  143.             Settings.System.putString(ctRes,Settings.System.WIFI_STATIC_DNS1,”192.168.0.1”); 
  144.             Settings.System.putString(ctRes, Settings.System.WIFI_STATIC_DNS2,”61.134.1.9”); 
  145.         } 
  146.         else 
  147.         {*/  
  148.             //如果是andoir3.x版本及以上的话  
  149.             try {  
  150.                 setIpAssignment(”STATIC”, wifiConfig);  
  151.                 setIpAddress(InetAddress.getByName(”192.168.0.202”),24, wifiConfig);  
  152.                 setGateway(InetAddress.getByName(”192.168.0.1”), wifiConfig);  
  153.                 setDNS(InetAddress.getByName(”192.168.0.1”), wifiConfig);  
  154.                 //apply the setting  
  155.                 wifiManager.updateNetwork(wifiConfig);  
  156.                 System.out.println(”静态ip设置成功”);  
  157.                 Toast.makeText(getApplicationContext(), ”成功”2).show();  
  158.             } catch (Exception  e) {  
  159.                 // TODO Auto-generated catch block  
  160.                 e.printStackTrace();  
  161.                 System.out.println(”静态ip设置失败”);  
  162.                 Toast.makeText(getApplicationContext(), ”失败”2).show();  
  163.             }   
  164.               
  165.         }  
  166.         /*}*/  
  167.     }  
package com.example.iptest;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.net.InetAddress;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.content.Context;import android.net.wifi.WifiConfiguration;import android.net.wifi.WifiInfo;import android.net.wifi.WifiManager;import android.os.Build;import android.os.Bundle;import android.widget.Toast;public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        System.out.println(android.os.Build.VERSION.SDK_INT);        setIpWithTfiStaticIp();    }/*  设置ip地址类型 assign: STATIC/DHCP 静态/动态*/  private static void setIpAssignment(String assign, WifiConfiguration wifiConf) throws SecurityException,IllegalArgumentException,NoSuchFieldException,IllegalAccessException, InvocationTargetException, NoSuchMethodException    {        if (Build.VERSION.SDK_INT >= 21) {            Object ipConfiguration = wifiConf.getClass()                    .getMethod("getIpConfiguration").invoke(wifiConf);            setEnumField(ipConfiguration, assign, "ipAssignment");        }    }//  设置ip地址    private static void setIpAddress(InetAddress addr,int prefixLength,WifiConfiguration wificonf) throws SecurityException,IllegalArgumentException,NoSuchFieldException,IllegalAccessException,NoSuchMethodException,ClassNotFoundException,InstantiationException,InvocationTargetException    {        Object linkProperties=getField(wificonf,"linkProperties");        if(linkProperties==null)        {            return;        }            Class<?> laClass=Class.forName("android.net.LinkAddress");            Constructor<?> laConstructor=laClass.getConstructor(new Class[]{                    InetAddress.class,int.class            });         Object linkAddress=laConstructor.newInstance(addr,prefixLength);         ArrayList<Object> mLinkAddresses=(ArrayList<Object>)getDeclaredField(linkProperties,"mLinkAddresses");         mLinkAddresses.clear();         mLinkAddresses.add(linkAddress);    }    @SuppressWarnings("unchecked")//  设置网关    private static void setGateway(InetAddress gateway, WifiConfiguration wifiConf) throws SecurityException,IllegalArgumentException,NoSuchFieldException,IllegalAccessException,ClassNotFoundException,NoSuchMethodException,InstantiationException,InvocationTargetException    {        Object linkProperties=getField(wifiConf,"linkProperties");        if(linkProperties==null)        {            return;        }        if(android.os.Build.VERSION.SDK_INT>=14)        {            //android4.x版本            Class<?> routeInfoClass=Class.forName("android.net.RouteInfo");            Constructor<?> routeInfoConstructor=routeInfoClass.getConstructor(new Class[]{InetAddress.class});            Object routeInfo=routeInfoConstructor.newInstance(gateway);            ArrayList<Object> mRoutes=(ArrayList<Object>)getDeclaredField(linkProperties,"mRoutes");            mRoutes.clear();            mRoutes.add(routeInfo);        }        /*else        {            //android 3.x版本            ArrayList<InetAddress> mGateways=(ArrayList<InetAddress>)getDeclaredField(linkProperties,"mGateways");            mGateways.clear();            mGateways.add(gateway);        }*/    }    @SuppressWarnings("unchecked")    //设置域名解析服务器    private static void setDNS(InetAddress dns,WifiConfiguration wifiConf) throws SecurityException,IllegalArgumentException,NoSuchFieldException,IllegalAccessException{        Object linkProperties=getField(wifiConf,"linkProperties");        if(linkProperties==null)        {            return;        }        ArrayList<InetAddress> mDnses=(ArrayList<InetAddress>)getDeclaredField(linkProperties,"mDnses");        //清除原有Dns设置(如果只想增加,不想清除,词句可省略)        mDnses.clear();        //增加新的DNS        mDnses.add(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 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({"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>)f.getType(),value));    }    //以上是android3.x以上设置静态ip地址的方法    //下面是调用方法    private void setIpWithTfiStaticIp()    {        WifiConfiguration wifiConfig=null;        WifiManager wifiManager=(WifiManager)getSystemService(Context.WIFI_SERVICE);        WifiInfo connectionInfo=wifiManager.getConnectionInfo();        List<WifiConfiguration> configuredNetworks=wifiManager.getConfiguredNetworks();        for (WifiConfiguration conf : configuredNetworks) {            if (conf.networkId==connectionInfo.getNetworkId()) {                wifiConfig=conf;                break;            }        }        /*if(android.os.Build.VERSION.SDK_INT<11)        {            //如果是android2.x版本的话            ContentResolver ctRes=this.getContentResolver();            Settings.System.putInt(ctRes, Settings.System.WIFI_USE_STATIC_IP,1);            Settings.System.putString(ctRes, Settings.System.WIFI_STATIC_IP,"192.168.0.202");            Settings.System.putString(ctRes, Settings.System.WIFI_STATIC_NETMASK,"255.255.255.0");            Settings.System.putString(ctRes, Settings.System.WIFI_STATIC_GATEWAY,"192.168.0.1");            Settings.System.putString(ctRes,Settings.System.WIFI_STATIC_DNS1,"192.168.0.1");            Settings.System.putString(ctRes, Settings.System.WIFI_STATIC_DNS2,"61.134.1.9");        }        else        {*/            //如果是andoir3.x版本及以上的话            try {                setIpAssignment("STATIC", wifiConfig);                setIpAddress(InetAddress.getByName("192.168.0.202"),24, wifiConfig);                setGateway(InetAddress.getByName("192.168.0.1"), wifiConfig);                setDNS(InetAddress.getByName("192.168.0.1"), wifiConfig);                //apply the setting                wifiManager.updateNetwork(wifiConfig);                System.out.println("静态ip设置成功");                Toast.makeText(getApplicationContext(), "成功", 2).show();            } catch (Exception  e) {                // TODO Auto-generated catch block                e.printStackTrace();                System.out.println("静态ip设置失败");                Toast.makeText(getApplicationContext(), "失败", 2).show();            }         }        /*}*/    }

//android5.x修改静态ip的方法

[java] view plain copy
print?在CODE上查看代码片派生到我的代码片
  1. package com.example.iptest;  
  2.   
  3. import java.lang.reflect.Constructor;  
  4. import java.lang.reflect.Field;  
  5. import java.lang.reflect.InvocationTargetException;  
  6. import java.lang.reflect.Method;  
  7. import java.net.InetAddress;  
  8. import java.net.UnknownHostException;  
  9. import java.util.ArrayList;  
  10. import java.util.List;  
  11.   
  12. import android.net.wifi.WifiConfiguration;  
  13. import android.net.wifi.WifiInfo;  
  14. import android.net.wifi.WifiManager;  
  15. import android.os.Build;  
  16. import android.os.Bundle;  
  17. import android.app.Activity;  
  18. import android.content.Context;  
  19. import android.view.Menu;  
  20.   
  21. public class OOActivity extends Activity {  
  22.   
  23.     @Override  
  24.     protected void onCreate(Bundle savedInstanceState) {  
  25.         super.onCreate(savedInstanceState);  
  26.         setContentView(R.layout.activity_oo);  
  27.         WifiConfiguration wifiConfig=null;  
  28.         WifiManager wifiManager=(WifiManager)getSystemService(Context.WIFI_SERVICE);  
  29.         WifiInfo connectionInfo=wifiManager.getConnectionInfo();  
  30.         List<WifiConfiguration> configuredNetworks=wifiManager.getConfiguredNetworks();  
  31.         for (WifiConfiguration conf : configuredNetworks) {  
  32.             if (conf.networkId==connectionInfo.getNetworkId()) {  
  33.                 wifiConfig=conf;  
  34.                 break;  
  35.             }  
  36.         }  
  37.       
  38.         try {  
  39.             setStaticIpConfiguration(wifiManager, wifiConfig, InetAddress.getByName(”192.168.0.202”), 24, InetAddress.getByName(“192.168.0.202”), InetAddress.getAllByName(“192.168.0.202”));  
  40.         } catch (ClassNotFoundException e) {  
  41.             // TODO Auto-generated catch block  
  42.             e.printStackTrace();  
  43.         } catch (IllegalAccessException e) {  
  44.             // TODO Auto-generated catch block  
  45.             e.printStackTrace();  
  46.         } catch (IllegalArgumentException e) {  
  47.             // TODO Auto-generated catch block  
  48.             e.printStackTrace();  
  49.         } catch (InvocationTargetException e) {  
  50.             // TODO Auto-generated catch block  
  51.             e.printStackTrace();  
  52.         } catch (NoSuchMethodException e) {  
  53.             // TODO Auto-generated catch block  
  54.             e.printStackTrace();  
  55.         } catch (NoSuchFieldException e) {  
  56.             // TODO Auto-generated catch block  
  57.             e.printStackTrace();  
  58.         } catch (InstantiationException e) {  
  59.             // TODO Auto-generated catch block  
  60.             e.printStackTrace();  
  61.         } catch (UnknownHostException e) {  
  62.             // TODO Auto-generated catch block  
  63.             e.printStackTrace();  
  64.         }  
  65.     }  
  66.   
  67.     public static void setStaticIpConfiguration(WifiManager manager,  
  68.             WifiConfiguration config, InetAddress ipAddress, int prefixLength,  
  69.             InetAddress gateway, InetAddress[] dns)  
  70.             throws ClassNotFoundException, IllegalAccessException,  
  71.             IllegalArgumentException, InvocationTargetException,  
  72.             NoSuchMethodException, NoSuchFieldException, InstantiationException {  
  73.         // First set up IpAssignment to STATIC.  
  74.         Object ipAssignment = getEnumValue(  
  75.                 ”android.net.IpConfigurationIpAssignment"</span><span>,&nbsp;</span><span class="string">"STATIC"</span><span>);&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;callMethod(config,&nbsp;<span class="string">"setIpAssignment"</span><span>,&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">new</span><span>&nbsp;String[]&nbsp;{&nbsp;</span><span class="string">"android.net.IpConfigurationIpAssignment” },  
  76.                 new Object[] { ipAssignment });  
  77.   
  78.         // Then set properties in StaticIpConfiguration.  
  79.         Object staticIpConfig = newInstance(”android.net.StaticIpConfiguration”);  
  80.         Object linkAddress = newInstance(”android.net.LinkAddress”,  
  81.                 new Class[] { InetAddress.classint.class }, new Object[] {  
  82.                         ipAddress, prefixLength });  
  83.   
  84.         setField(staticIpConfig, ”ipAddress”, linkAddress);  
  85.         setField(staticIpConfig, ”gateway”, gateway);  
  86.         
  87.        ArrayList<Object> aa= (ArrayList<Object>) getField(staticIpConfig, ”dnsServers”);  
  88.        aa.clear();  
  89.         for (int i = 0; i < dns.length; i++)  
  90.             aa.add(dns[i]);  
  91.         callMethod(config, ”setStaticIpConfiguration”,  
  92.                 new String[] { “android.net.StaticIpConfiguration” },  
  93.                 new Object[] { staticIpConfig });  
  94.         manager.updateNetwork(config);  
  95.         manager.saveConfiguration();  
  96.         System.out.println(”ttttttttttt”+“成功”);  
  97.     }  
  98.   
  99.     private static Object newInstance(String className)  
  100.             throws ClassNotFoundException, InstantiationException,  
  101.             IllegalAccessException, NoSuchMethodException,  
  102.             IllegalArgumentException, InvocationTargetException {  
  103.         return newInstance(className, new Class[0], new Object[0]);  
  104.     }  
  105.   
  106.     private static Object newInstance(String className,  
  107.             Class[] parameterClasses, Object[] parameterValues)  
  108.             throws NoSuchMethodException, InstantiationException,  
  109.             IllegalAccessException, IllegalArgumentException,  
  110.             InvocationTargetException, ClassNotFoundException {  
  111.         Class clz = Class.forName(className);  
  112.         Constructor constructor = clz.getConstructor(parameterClasses);  
  113.         return constructor.newInstance(parameterValues);  
  114.     }  
  115.   
  116.     @SuppressWarnings({ “unchecked”“rawtypes” })  
  117.     private static Object getEnumValue(String enumClassName, String enumValue)  
  118.             throws ClassNotFoundException {  
  119.         Class enumClz = (Class) Class.forName(enumClassName);  
  120.         return Enum.valueOf(enumClz, enumValue);  
  121.     }  
  122.   
  123.     private static void setField(Object object, String fieldName, Object value)  
  124.             throws IllegalAccessException, IllegalArgumentException,  
  125.             NoSuchFieldException {  
  126.         Field field = object.getClass().getDeclaredField(fieldName);  
  127.         field.set(object, value);  
  128.     }  
  129.   
  130.     private static  Object getField(Object object, String fieldName)  
  131.             throws IllegalAccessException, IllegalArgumentException,  
  132.             NoSuchFieldException {  
  133.         Field field = object.getClass().getDeclaredField(fieldName);  
  134.         Object out = field.get(object);  
  135.         return out;  
  136.     }  
  137.   
  138.     private static void callMethod(Object object, String methodName,  
  139.             String[] parameterTypes, Object[] parameterValues)  
  140.             throws ClassNotFoundException, IllegalAccessException,  
  141.             IllegalArgumentException, InvocationTargetException,  
  142.             NoSuchMethodException {  
  143.         Class[] parameterClasses = new Class[parameterTypes.length];  
  144.         for (int i = 0; i < parameterTypes.length; i++)  
  145.             parameterClasses[i] = Class.forName(parameterTypes[i]);  
  146.   
  147.         Method method = object.getClass().getDeclaredMethod(methodName,  
  148.                 parameterClasses);  
  149.         method.invoke(object, parameterValues);  
  150.     }  
  151.   
  152. //直接使用set方法调用 可能遇到需要地址转换方法如下:  
  153. public static String int2ip(int ip) {  
  154.         StringBuilder sb = new StringBuilder();  
  155.         sb.append(String.valueOf((int) (ip & 0xff)));  
  156.         sb.append(’.’);  
  157.         sb.append(String.valueOf((int) ((ip >> 8) & 0xff)));  
  158.         sb.append(’.’);  
  159.         sb.append(String.valueOf((int) ((ip >> 16) & 0xff)));  
  160.         sb.append(’.’);  
  161.         sb.append(String.valueOf((int) ((ip >> 24) & 0xff)));  
  162.         return sb.toString();  
  163.     }  
  164.   
  165. }  
package com.example.iptest;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.net.InetAddress;import java.net.UnknownHostException;import java.util.ArrayList;import java.util.List;import android.net.wifi.WifiConfiguration;import android.net.wifi.WifiInfo;import android.net.wifi.WifiManager;import android.os.Build;import android.os.Bundle;import android.app.Activity;import android.content.Context;import android.view.Menu;public class OOActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_oo);        WifiConfiguration wifiConfig=null;        WifiManager wifiManager=(WifiManager)getSystemService(Context.WIFI_SERVICE);        WifiInfo connectionInfo=wifiManager.getConnectionInfo();        List<WifiConfiguration> configuredNetworks=wifiManager.getConfiguredNetworks();        for (WifiConfiguration conf : configuredNetworks) {            if (conf.networkId==connectionInfo.getNetworkId()) {                wifiConfig=conf;                break;            }        }        try {            setStaticIpConfiguration(wifiManager, wifiConfig, InetAddress.getByName("192.168.0.202"), 24, InetAddress.getByName("192.168.0.202"), InetAddress.getAllByName("192.168.0.202"));        } catch (ClassNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IllegalAccessException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IllegalArgumentException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (InvocationTargetException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (NoSuchMethodException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (NoSuchFieldException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (InstantiationException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (UnknownHostException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    public static void setStaticIpConfiguration(WifiManager manager,            WifiConfiguration config, InetAddress ipAddress, int prefixLength,            InetAddress gateway, InetAddress[] dns)            throws ClassNotFoundException, IllegalAccessException,            IllegalArgumentException, InvocationTargetException,            NoSuchMethodException, NoSuchFieldException, InstantiationException {        // First set up IpAssignment to STATIC.        Object ipAssignment = getEnumValue(                "android.net.IpConfiguration$IpAssignment", "STATIC");        callMethod(config, "setIpAssignment",                new String[] { "android.net.IpConfiguration$IpAssignment" },                new Object[] { ipAssignment });        // Then set properties in StaticIpConfiguration.        Object staticIpConfig = newInstance("android.net.StaticIpConfiguration");        Object linkAddress = newInstance("android.net.LinkAddress",                new Class[] { InetAddress.class, int.class }, new Object[] {                        ipAddress, prefixLength });        setField(staticIpConfig, "ipAddress", linkAddress);        setField(staticIpConfig, "gateway", gateway);       ArrayList<Object> aa= (ArrayList<Object>) getField(staticIpConfig, "dnsServers");       aa.clear();        for (int i = 0; i < dns.length; i++)            aa.add(dns[i]);        callMethod(config, "setStaticIpConfiguration",                new String[] { "android.net.StaticIpConfiguration" },                new Object[] { staticIpConfig });        manager.updateNetwork(config);        manager.saveConfiguration();        System.out.println("ttttttttttt"+"成功");    }    private static Object newInstance(String className)            throws ClassNotFoundException, InstantiationException,            IllegalAccessException, NoSuchMethodException,            IllegalArgumentException, InvocationTargetException {        return newInstance(className, new Class[0], new Object[0]);    }    private static Object newInstance(String className,            Class[] parameterClasses, Object[] parameterValues)            throws NoSuchMethodException, InstantiationException,            IllegalAccessException, IllegalArgumentException,            InvocationTargetException, ClassNotFoundException {        Class clz = Class.forName(className);        Constructor constructor = clz.getConstructor(parameterClasses);        return constructor.newInstance(parameterValues);    }    @SuppressWarnings({ "unchecked", "rawtypes" })    private static Object getEnumValue(String enumClassName, String enumValue)            throws ClassNotFoundException {        Class enumClz = (Class) Class.forName(enumClassName);        return Enum.valueOf(enumClz, enumValue);    }    private static void setField(Object object, String fieldName, Object value)            throws IllegalAccessException, IllegalArgumentException,            NoSuchFieldException {        Field field = object.getClass().getDeclaredField(fieldName);        field.set(object, value);    }    private static  Object getField(Object object, String fieldName)            throws IllegalAccessException, IllegalArgumentException,            NoSuchFieldException {        Field field = object.getClass().getDeclaredField(fieldName);        Object out = field.get(object);        return out;    }    private static void callMethod(Object object, String methodName,            String[] parameterTypes, Object[] parameterValues)            throws ClassNotFoundException, IllegalAccessException,            IllegalArgumentException, InvocationTargetException,            NoSuchMethodException {        Class[] parameterClasses = new Class[parameterTypes.length];        for (int i = 0; i < parameterTypes.length; i++)            parameterClasses[i] = Class.forName(parameterTypes[i]);        Method method = object.getClass().getDeclaredMethod(methodName,                parameterClasses);        method.invoke(object, parameterValues);    }//直接使用set方法调用 可能遇到需要地址转换方法如下:public static String int2ip(int ip) {        StringBuilder sb = new StringBuilder();        sb.append(String.valueOf((int) (ip & 0xff)));        sb.append('.');        sb.append(String.valueOf((int) ((ip >> 8) & 0xff)));        sb.append('.');        sb.append(String.valueOf((int) ((ip >> 16) & 0xff)));        sb.append('.');        sb.append(String.valueOf((int) ((ip >> 24) & 0xff)));        return sb.toString();    }}

//参考博客

http://www.eoeandroid.com/thread-233453-1-1.html?_dsign=505ec204

http://www.ithao123.cn/content-8639527.html

http://blog.rgbtime.com/topic/60/nosuchfieldexecption-ipassignment

0 0
原创粉丝点击