Thursday, November 22, 2012

How to get device MAC ID in ANDROID

--------------------------------------------------------------------------
Using WifiManager get wifi mac id in android.
--------------------------------------------------------------------------

wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
macaddress = wifiManager.getConnectionInfo().getMacAddress();
Log.i("MACID in loading...", "" + macaddress);

---------------------------------------------------------------------


@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Using java.Utils package we can get MAC ID of device...

This is a code available in an Utils pkg.
We can add only this following class in our project...

---------------------------------------------------------------------

import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.http.conn.util.InetAddressUtils;

public class RanjitUtils {

 /**
* Returns MAC address of the given interface name.
*
* @param interfaceName
*            eth0, wlan0 or NULL=use first interface
* @return mac address or empty string
*/
public static String getMACAddress(String interfaceName) {
try {
List<NetworkInterface> interfaces = Collections
.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (interfaceName != null) {
if (!intf.getName().equalsIgnoreCase(interfaceName))
continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac == null)
return "";
StringBuilder buf = new StringBuilder();
for (int idx = 0; idx < mac.length; idx++)
buf.append(String.format("%02X:", mac[idx]));
if (buf.length() > 0)
buf.deleteCharAt(buf.length() - 1);
return buf.toString();
}
} catch (Exception ex) {
} // for now eat exceptions
return "";
/*
* try { // this is so Linux hack return
* loadFileAsString("/sys/class/net/" +interfaceName +
* "/address").toUpperCase().trim(); } catch (IOException ex) { return
* null; }
*/
}
}
----------------------------------------------
access getMACADDRES(String) static method
----------------------------------------------
String macid_eth = RanjitUtils.getMACAddress("eth0");
or
String macid_wlan = RanjitUtils.getMACAddress("wlan0");

No comments:

Post a Comment