標籤:android style blog class code java tar ext javascript color get
由於WiFi 的Mac address 是一個被動諮詢。一般在開機後,不會主動上到的系統裡。要等待WiFi硬體啟動後,才會把有關Mac address資料記載入系統去。 所以一般android系統擷取Mac address時候會出現以下幾種情況:
1、在WiFi開啟的時候可以擷取到Mac地址
2、關閉WiFi,不重啟系統,也可以擷取到Mac address
3、系統重啟後,不開啟WiFi,擷取不到Mac address
4、系統重啟後,不開開WiFi,開啟2G、3G網路,擷取不到Mac address
要擷取Mac address :1、等待WiFi啟動
2、在程式中主動啟動WiFi
第二種情況代碼如下:
1 public String macAddress = null; 2 3 public void getWifiMacAddress(Context context) { 4 final WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); 5 if (wifi == null) 6 return; 7 WifiInfo info = wifi.getConnectionInfo(); 8 this.macAddress = info.getMacAddress(); 9 10 if (this.macAddress == null && !wifi.isWifiEnabled()) {11 new Thread() {12 @Override13 public void run() {14 wifi.setWifiEnabled(true);15 for (int i = 0; i < 10; i++) {16 WifiInfo _info = wifi.getConnectionInfo();17 macAddress = _info.getMacAddress();18 if (macAddress != null)19 break;20 try {21 Thread.sleep(500);22 } catch (InterruptedException e) {23 // TODO Auto-generated catch block24 e.printStackTrace();25 }26 }27 wifi.setWifiEnabled(false);28 }29 }.start();30 31 System.out.println("getmac:" + macAddress);32 }33 }
AndroidManifest.xml 中設定一下許可權:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>