如何使用Java代碼擷取Android移動終端Mac地址,android移動終端
快下班了,現在總結一下如何使用Java代碼擷取Android移動終端Mac地址:
通過裝置開通WiFi串連擷取Mac地址是最可取的,代碼如下:
/** * 裝置開通WiFi串連,通過wifiManager擷取Mac地址 * * @author 高煥傑 */public static String getMacFromWifi(Context context){ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);State wifiState = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();if(wifiState == NetworkInfo.State.CONNECTED){//判斷當前是否使用wifi串連 WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { //如果當前wifi不可用 wifiManager.setWifiEnabled(true); } WifiInfo wifiInfo = wifiManager.getConnectionInfo(); return wifiInfo.getMacAddress();} return null;} 除了上面這種方法,網上還給出了另外兩種方法:
1、通過調用Linux的busybox命令擷取Mac地址:
/** * 通過調用Linux的busybox命令擷取Mac地址 * * @author 高煥傑 */private static String getMacFromCallCmd(){ try { String readLine = ""; Process process = Runtime.getRuntime().exec("busybox ifconfig"); BufferedReader bufferedReader = new BufferedReader (new InputStreamReader(process.getInputStream())); while ((readLine = bufferedReader.readLine ()) != null) {//執行命令cmd,只取結果中含有"HWaddr"的這一行 if(readLine.contains("HWaddr")){ return readLine.substring(readLine.indexOf("HWaddr")+6, readLine.length()-1); } } }catch(Exception e) { //如果因裝置不支援busybox工具而發生異常。 e.printStackTrace(); } return null;} 注意:這種方法在Android Pad中可以準確擷取到的Mac地址,但是在Android手機中無法準確擷取到。
2、通過查詢記錄了MAC地址的檔案(檔案路徑:“/proc/net/arp”)擷取Mac地址:
/** * 通過查詢記錄了MAC地址的檔案(檔案路徑:“/proc/net/arp”)擷取Mac地址 * * @author 高煥傑 */ private static String getMacFromFile(Context context){ String readLine =""; BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(new File("/proc/net/arp"))); int rollIndex = 0; while((readLine = bufferedReader.readLine())!=null){ if(rollIndex == 1){ break; } rollIndex = rollIndex + 1; } } catch (IOException e) { e.printStackTrace(); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } if(readLine !=null && readLine.length()>1){ String[] subReadLineArray = readLine.split(" "); int rollIndex = 1; for(int i = 0; i < subReadLineArray.length; ++i){ if(!TextUtils.isEmpty(subReadLineArray[i])){ if(rollIndex == 4){ return subReadLineArray[i]; } rollIndex = rollIndex + 1; } } } return null; } 注意:無論在Android Pad中還是在Android手機中,這種方法都無法準確擷取到Mac地址。
【0分下載樣本】