get Mac Address from WifiManager and /sys/class/net/wlan0/address - Android android.net.wifi

Android examples for android.net.wifi:WifiManager

Description

get Mac Address from WifiManager and /sys/class/net/wlan0/address

Demo Code

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

public class Main {

  public static String getMacAddress(Context activity) {
    String macSerial = null;//w ww  . j a v a 2  s  .com
    try {
      WifiManager wifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
      WifiInfo info = wifi.getConnectionInfo();
      macSerial = info.getMacAddress();
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (macSerial == null) {
      macSerial = getMac();
    }
    return macSerial;
  }

  private static String getMac() {
    String macSerial = "";
    String str = "";
    try {
      Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
      InputStreamReader ir = new InputStreamReader(pp.getInputStream());
      LineNumberReader input = new LineNumberReader(ir);

      for (; null != str;) {
        str = input.readLine();
        if (str != null) {
          macSerial = str.trim();
          break;
        }
      }
    } catch (IOException ex) {

      ex.printStackTrace();
    }
    return macSerial;
  }

}

Related Tutorials