- 摘自:http://blog.youkuaiyun.com/zxw136511485/article/details/52161269
-
- 我们在实际开发中,需要使用 MAC地址,以下方式不管是在6.0,还是在低版本都可以获取到 MAC地址。
- /**
- * 获取Mac地址
- */
- public class MacUtils {
- /**
- * 获取手机的MAC地址
- *
- * @return
- */
- public static String getMac() {
- String str = "";
- String macSerial = "";
- try {
- Process pp = Runtime.getRuntime().exec(
- "cat /sys/class/net/wlan0/address ");
- InputStreamReader ir = new InputStreamReader(pp.getInputStream());
- LineNumberReader input = new LineNumberReader(ir);
- for (; null != str;) {
- str = input.readLine();
- if (str != null) {
- macSerial = str.trim();// 去空格
- break;
- }
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- if (macSerial == null || "".equals(macSerial)) {
- try {
- return loadFileAsString("/sys/class/net/eth0/address")
- .toUpperCase().substring(0, 17);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return macSerial;
- }
- public static String loadFileAsString(String fileName) throws Exception {
- FileReader reader = new FileReader(fileName);
- String text = loadReaderAsString(reader);
- reader.close();
- return text;
- }
- public static String loadReaderAsString(Reader reader) throws Exception {
- StringBuilder builder = new StringBuilder();
- char[] buffer = new char[4096];
- int readLength = reader.read(buffer);
- while (readLength >= 0) {
- builder.append(buffer, 0, readLength);
- readLength = reader.read(buffer);
- }
- return builder.toString();
- }
- }
经测试,该代码在6.0和4.x版本上都可以获取到真实的MAC地址。
PS:在6.0上需要AndroidManifest.xml在加入以下2个权限,