本文实例讲述了Android编程获取设备MAC地址的实现方法。分享给大家供大家参考,具体如下:
/**
* 获取设备的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();
}
SimpleCallback是一个简单的回调接口:
public interface SimpleCallback {
void onComplete(String result);
}
希望本文所述对大家Android程序设计有所帮助。