Get the Wifi Mac address. - Android Phone

Android examples for Phone:wifi

Description

Get the Wifi Mac address.

Demo Code


//package com.java2s;

import android.content.Context;

import android.net.wifi.WifiManager;

import android.provider.Settings;
import android.telephony.TelephonyManager;

public class Main {
    /** Get the Wifi Mac address. If wifi is not available, use device id instead */
    public static String getMacAddress(Context context) {
        WifiManager wimanager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        String macAddress = wimanager.getConnectionInfo().getMacAddress();
        if (macAddress == null) {
            macAddress = getDeviceId(context);
        }//from   w w w.j  a  v  a 2  s .  c  om
        return macAddress;
    }

    /** Get unique deviceId  */
    public static String getDeviceId(final Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String id = telephonyManager.getDeviceId();

        if (id == null || id.isEmpty())
            id = telephonyManager.getSubscriberId();

        if (id == null || id.isEmpty())
            id = telephonyManager.getSimSerialNumber();

        if (id == null || id.isEmpty()) {
            WifiManager m_wm = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            if (m_wm != null)
                id = m_wm.getConnectionInfo().getMacAddress();
        }

        if (id == null || id.isEmpty())
            id = Settings.Secure.getString(context.getContentResolver(),
                    Settings.Secure.ANDROID_ID);

        if (id == null || id.isEmpty())
            id = telephonyManager.getDeviceId();

        return id;
    }
}

Related Tutorials