赞
踩
获取Android手机MAC的一种实现方案,仅供参考,哈哈哈!是否还有其他更优的解决方法呢?
请注意,高版本在WiFi关闭时,获取不到MAC
`
/**
* 获取手机MAC;
* @param context
* @return
*/
public static String getWlanMac(Context context){ String mac = getWlanMacWifiManager(context); if(mac == null){ //从本地文件获取 mac = getWlanMacLocalAddress(); if(mac == null){ //从java网络接口获取 mac = getWlanMacInterface(); if(mac == null){ //最后从缓存里读取 mac = Pref.getString("wlan_mac_cached", context); } } } if(mac != null){ //缓存mac值,防止后续获取失败;一般MAC不会改变 Pref.saveString("wlan_mac_cached", mac, context); } return mac; /** * 从WifiManager接口获取手机MAC; * @param context * @return */ public static String getWlanMacWifiManager(Context context){ Log.i("DeviceUtil","get mac by WifiManager..."); String mac = null; WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); boolean isWifiEnabled = wifiManager.isWifiEnabled(); if(!isWifiEnabled){ //6.0以上版本获取需要等待授权,所以下面的读取语句会执行失败 wifiManager.setWifiEnabled(true); } if (isWifiEnabled) { WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo != null) { mac = wifiInfo.getMacAddress(); if(CheckUtils.isMacRight(mac)){ Log.i("DeviceUtil","mac = " + mac); return mac; }else{ mac = null; } } } return mac; } /** * 从本地文件获取手机MAC; * @param context * @return */ public static String getWlanMacLocalAddress(){ Log.i("DeviceUtil","get mac by local address..."); String mac = null; String path = "/sys/class/net/wlan0/address"; File wlan0 = new File(path); if(wlan0.exists() && wlan0.isFile()){ mac = execCmd("cat " + path); if (CheckUtils.isMacRight(mac)) { return mac; }else{ mac = null; } } return mac; } private static String getWlanMacInterface() { Log.i("DeviceUtil","get mac by new interface..." ); String mac = null; try { List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface nif : all) { if (!nif.getName().equalsIgnoreCase("wlan0")) { continue; } byte[] macBytes = nif.getHardwareAddress(); if (macBytes == null) { return mac; } StringBuilder builder = new StringBuilder(); for (byte b : macBytes) { builder.append(String.format("%02X:",b)); } if (builder.length() > 0) { builder.deleteCharAt(builder.length() - 1); } mac = builder.toString(); Log.i("DeviceUtil","mac = " + mac); } } catch (Exception e) { e.printStackTrace(); } return mac; }
`
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。