android机顶盒上一般有两个网卡,一个有线一个无线,那么在获取mac地址来唯一标识一台终端的时候取那个呢?经过讨论,取有线的Mac地址。但是当前如果我只用的是wifi呢?怎么取有线网卡的mac地址,经过观察settings里面的源码,发现了获取有线网卡mac地址的方法,即使当前机顶盒连接时wifi,如下:
public String getEth0HW(){
EthernetManager ethManager = (EthernetManager) getSystemService(Context.ETHERNET_SERVICE);
String str = ethManager.getEthernetHwaddr(ethManager.getEthernetIfaceName());
if(null == str){
str = "null";
}
return str ;
}
/**
* 获取wifi模块的mac地址,即使wifi是关闭的,需要添加权限 ACCESS_WIFI_STATE
* @param context
* @return
*/
public static String getWifiMac(Context context){
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String mac = info.getMacAddress();
Log.e("","wifi mac : " + mac);
return mac ;
}
获取当前连接网络的网卡的mac地址
private static String parseByte(byte b) {
String s = "00" + Integer.toHexString(b)+":";
return s.substring(s.length() - 3);
}
/**
* 获取当前系统连接网络的网卡的mac地址
* @return
*/
@SuppressLint("NewApi")
public static final String getMac() {
byte[] mac = null;
StringBuffer sb = new StringBuffer();
try {
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
InetAddress ip = address.nextElement();
if (ip.isAnyLocalAddress() || !(ip instanceof Inet4Address) || ip.isLoopbackAddress())
continue;
if (ip.isSiteLocalAddress())
mac = ni.getHardwareAddress();
else if (!ip.isLinkLocalAddress()) {
mac = ni.getHardwareAddress();
break;
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
if(mac != null){
for(int i=0 ;i<mac.length ;i++){
sb.append(parseByte(mac[i]));
}
return sb.substring(0, sb.length()-1);
}else{
return UpdateService.mDefaultMacAddress;
}
}
}