Search code examples
androidandroid-wifi

getMacAddress() is returning null


This is the code snippet that I use

public static String getMACAddressOfDevice(Context context){
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String macAddress = wifiInfo.getMacAddress();
        return macAddress;
    }

sometime it returns null.I don't understand why ! Can anybody explain me ?


Solution

  • When wifi is switched off , some android device returns null.

    It's in current design.

    If the device doesn't have wifi hardware , then this approach doesn't work.

    There are some other alternatives for unique identification of devices

    IMEI:

    TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
    String m_deviceId = TelephonyMgr.getDeviceId();
    

    Drawbacks:

    It is sim card dependent so

    • If there is no sim card then we're doomed

    • If there is dual sim then we're dommed

    Bluetooth address:

    BluetoothAdapter m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
       String m_bluetoothAdd = m_BluetoothAdapter.getAddress();
    

    Drawbacks:

    • if there is no bluetooth hardware we're doomed.
    • In future in some new devices we mightn't able to read it if its off.

    Serial:

    We can read the hardware serial number.It can be seen in the device settings.

     Build.SERIAL
    

    Drawbacks:

    • If the device doesn't have telephony,this can't be used.There are some wifi-only devices are available in market.

    Android_ID:

    You can try using the ANDROID_ID its good for unique identification of the devices since its not dependent on any hardware IMEI

    String m_androidId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
    

    Drawbacks:

    • If OS version is upgraded then it may change
    • If device is rooted it gets changed
    • No guarantee that the device_id is unique there are some reports some manufacturers are having duplicate device_id

    Suggestion:

    The safest bet is to use Android_ID because it's not dependent on availability of any hardware

    Reference