android 读取mac地址

android 读取mac地址,有两种方式:

1.
public String macAddress=null;
 
public void getWifiMacAddress(Context context) {
  final WifiManager wifi=(WifiManager)c.getSystemService(Context.WIFI_SERVICE);
  if(wifi==null) return;
 
  WifiInfo info=wifi.getConnectionInfo();
  this.macAddress=info.getMacAddress();
                 
  if(this.macAddress==null && !wifi.isWifiEnabled()) {
    new Thread() {
      @Override
      public void run() {
        wifi.setWifiEnabled(true);
        for(int i=0;i<10;i++) {
          WifiInfo _info=wifi.getConnectionInfo();
          macAddress=_info.getMacAddress();
          if(macAddress!=null) break;
          Thread.sleep(500);
        }
        wifi.setWifiEnabled(false);
      }
    }.start();
  }
}

要留意需要下边的Permission
    <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>

  
2.
/*
 * Load file content to String
 */
public static String loadFileAsString(String filePath) throws java.io.IOException{
    StringBuffer fileData = new StringBuffer(1000);
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    char[] buf = new char[1024];
    int numRead=0;
    while((numRead=reader.read(buf)) != -1){
        String readData = String.valueOf(buf, 0, numRead);
        fileData.append(readData);
    }
    reader.close();
    return fileData.toString();
}
 
/*
 * Get the STB MacAddress
 */
public String getMacAddress(){
    try {
        return loadFileAsString("/sys/class/net/eth0/address")
            .toUpperCase().substring(0, 17);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

你可能感兴趣的:(android)