Android examples for Phone:Network
get MAC Address
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import java.util.List; import android.app.ActivityManager; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.provider.Settings.Secure; public class Main{ /* ww w. j a v a 2s.c om*/ public static String getMACAddress(Context context) { if (mac != null && mac.length() > 0) { return mac; } if (context == null) { return ""; } else { ConnectivityManager conMan = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); State wifi_state = conMan.getNetworkInfo( ConnectivityManager.TYPE_WIFI).getState(); NetworkInfo networkInfo = conMan .getNetworkInfo(ConnectivityManager.TYPE_ETHERNET); State net_state = State.DISCONNECTED; if (networkInfo != null) { net_state = networkInfo.getState(); } if (wifi_state == State.CONNECTED) { WifiManager wifi = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifi.getConnectionInfo(); mac = info.getMacAddress(); } else if (net_state == State.CONNECTED) { mac = getEthernetNetworkMACAddress(); } } return mac; } public static String getEthernetNetworkMACAddress() { NetworkInterface NIC; StringBuffer mac = new StringBuffer(); try { NIC = NetworkInterface.getByName("eth0"); byte[] buf = NIC.getHardwareAddress(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { mac.append("0" + hex); } else { mac.append(hex); } } Log.e("DeviceUtil", "mac = " + mac.toString()); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } return mac.toString(); } }