由于网卡操作的部分API在Android 5.1上没有暴露,我们可以采取两种方案,一是通过反射的方式获取相应的api,二是从系统中获取完整的framework.jar
1、设置以太网动态获取IP
EthernetManager mEthManager = null;
mEthManager = (EthernetManager) context.getSystemService("ethernet");
mEthManager.setConfiguration(new IpConfiguration(IpConfiguration.IpAssignment.DHCP, IpConfiguration.ProxySettings.NONE,null,null));
2、设置以太网静态IP
/**
* 设置以太网静态IP地址
*
* @param address ip地址
* @param mask 子网掩码
* @param gate 网关
* @param dns1 dns1
*/
public static boolean setEthernetStaticIp(Context context, String address, String mask, String gate, String dns1, String dnsStr2) {
try {
EthernetManager mEthManager = null;
mEthManager = (EthernetManager) context.getSystemService("ethernet");
StaticIpConfiguration mStaticIpConfiguration =new StaticIpConfiguration();
IpConfiguration mIpConfiguration;
Inet4Address inetAddr = getIPv4Address(address);
int prefixLength = maskStr2InetMask(mask);
InetAddress gatewayAddr =getIPv4Address(gate);
InetAddress dnsAddr = getIPv4Address(dns1);
if (inetAddr.getAddress().toString().isEmpty() || prefixLength ==0 || gatewayAddr.toString().isEmpty()
|| dnsAddr.toString().isEmpty()) {
Log.e(MainActivity.TAG,"ip,mask or dnsAddr is wrong");
return false;
}
mStaticIpConfiguration.ipAddress = new LinkAddress(inetAddr, prefixLength);
mStaticIpConfiguration.gateway=gatewayAddr;
mStaticIpConfiguration.dnsServers.add(dnsAddr);
if (dnsStr2 != null && !dnsStr2.isEmpty()) {
mStaticIpConfiguration.dnsServers.add(getIPv4Address(dnsStr2));
}
mIpConfiguration=new IpConfiguration(IpConfiguration.IpAssignment.STATIC, IpConfiguration.ProxySettings.NONE,mStaticIpConfiguration,null);
mEthManager.setConfiguration(mIpConfiguration);
return true;
} catch (Exception e) {
return false;
}
}
3、获取以太网IP信息
public static int getNetInfo(Context context,String connectState,String ip,String mask,String gate,String dns1,String dns2)
{
int nRet = -1;
try{
EthernetManager mEthManager = null;
mEthManager = (EthernetManager) context.getSystemService("ethernet");
boolean useDhcp=(mEthManager.getConfiguration().ipAssignment == IpConfiguration.IpAssignment.DHCP) ? true : false;
if (useDhcp)
{
connectState = "dhcp";
}
else
{
connectState = "static";
}
StaticIpConfiguration staticIpConfiguration=mEthManager.getConfiguration().getStaticIpConfiguration();
if(staticIpConfiguration == null) {
return nRet;
}
LinkAddress ipAddress = staticIpConfiguration.ipAddress;
InetAddress gateway = staticIpConfiguration.gateway;
ArrayList<InetAddress> dnsServers=staticIpConfiguration.dnsServers;
if( ipAddress !=null) {
ip=ipAddress.getAddress().getHostAddress();
mask=interMask2String(ipAddress.getPrefixLength());
}
if(gateway !=null) {
gate=gateway.getHostAddress();
}
dns1=dnsServers.get(0).getHostAddress();
if(dnsServers.size() > 1) { /* 只保留两个*/
dns2=dnsServers.get(1).getHostAddress();
}
}catch (Exception e){
Log.w("EthernetIP", "getNetInfo() : e = " + e.toString());
}
return nRet;
}
以上就是Android 5.1上以太网使用的大致方法,小编已上传framework.jar,请自行下载