1. 程式人生 > >在安卓6.0(及以上)裝置上無法獲取無線網絡卡MAC地址的解決方案

在安卓6.0(及以上)裝置上無法獲取無線網絡卡MAC地址的解決方案

在安卓6.0以下的裝置上,通過WifiManager.getConnectionInfo().getMacAddress()即可獲取WLAN實體地址,

而在6.0及以上,以此方式獲取到的MAC地址為固定值02:00:00:00:00:00,而非真實值

解決方案

WlanMacAddressGetter.java

package com.example.buyishi.myapplication;

import android.util.Log;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class WlanMacAddressGetter { private static final String TAG = WlanMacAddressGetter.class.getName(); public static String getWlanMacAddress() { try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while
(networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); if (networkInterface.getName().equals("wlan0")) { StringBuilder mac = new StringBuilder(); byte[] hardwareAddress = networkInterface.getHardwareAddress(); String hex
= Integer.toHexString(hardwareAddress[0] & 0xff); if (hex.length() == 1) { mac.append('0'); } mac.append(hex); for (int i = 1; i < hardwareAddress.length; ++i) { mac.append(':'); hex = Integer.toHexString(hardwareAddress[i] & 0xff); if (hex.length() == 1) { mac.append('0'); } mac.append(hex); } return mac.toString(); } } } catch (SocketException ex) { Log.e(TAG, null, ex); } return null; } }

注意:須宣告許可權android.permission.INTERNET,否則在獲取MAC時會引發SocketException