您的位置:首页 > 移动开发 > Android开发

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

2016-12-21 10:44 127 查看
//android 3.x,4.x修改静态ip

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的方法
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: