參考自:http://www.open-open.com/lib/view/open1433406847322.htmlhtml
/** * 獲取設備的mac地址 * * @param ac * @param callback * 成功獲取到mac地址以後會回調此方法 */ public static void getMacAddress(final Activity ac, final SimpleCallback callback) { final WifiManager wm = (WifiManager) ac .getSystemService(Service.WIFI_SERVICE); // 若是本次開機後打開過WIFI,則可以直接獲取到mac信息。馬上返回數據。 WifiInfo info = wm.getConnectionInfo(); if (info != null && info.getMacAddress() != null) { if (callback != null) { callback.onComplete(info.getMacAddress()); } return; } // 嘗試打開WIFI,並獲取mac地址 if (!wm.isWifiEnabled()) { wm.setWifiEnabled(true); } new Thread(new Runnable() { @Override public void run() { int tryCount = 0; final int MAX_COUNT = 10; while (tryCount < MAX_COUNT) { final WifiInfo info = wm.getConnectionInfo(); if (info != null && info.getMacAddress() != null) { if (callback != null) { ac.runOnUiThread(new Runnable() { @Override public void run() { callback.onComplete(info.getMacAddress()); } }); } return; } SystemClock.sleep(300); tryCount++; } // 未獲取到mac地址 if (callback != null) { callback.onComplete(null); } } }).start(); }
public interface SimpleCallback { void onComplete(String result); }