Android Studio WiFi 之 获取 WiFi 名称、IP、Mac

Android 获取连接的WIFI 的一些数据(后期封装成aar 包给Unity 调用)

封装成AAR包,获取 Android 7.0 以上的 手机 mac 地址

一、Android 代码

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import android.text.format.Formatter;


import java.net.InetAddress;
import java.net.NetworkInterface;

import java.net.SocketException;
import java.util.Enumeration;

import static android.content.Context.WIFI_SERVICE;


public class WifiMgr {

   /*
   *获取Mac地址
   *
   * android 7.0 以上使用*/
    public static String getMacAddress() {
        String strMacAddr = null;
        try {
            // 获得IpD地址
            InetAddress ip = getLocalInetAddress();
            byte[] b = NetworkInterface.getByInetAddress(ip)
                    .getHardwareAddress();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < b.length; i++) {
                if (i != 0) {
                    buffer.append(':');
                }
                String str = Integer.toHexString(b[i] & 0xFF);
                buffer.append(str.length() == 1 ? 0 + str : str);
            }
            strMacAddr = buffer.toString().toUpperCase();
        } catch (Exception e) {
        }
        return strMacAddr;
    }
    /**
     * 获取移动设备本地IP
     *
     * @return
     */
    private static InetAddress getLocalInetAddress() {
        InetAddress ip = null;
        try {
            // 列举
            Enumeration<NetworkInterface> en_netInterface = NetworkInterface
                    .getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {// 是否还有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface
                        .nextElement();// 得到下一个元素
                Enumeration<InetAddress> en_ip = ni.getInetAddresses();// 得到一个ip地址的列举
                while (en_ip.hasMoreElements()) {
                    ip = en_ip.nextElement();
                    if (!ip.isLoopbackAddress()
                            && ip.getHostAddress().indexOf(":") == -1)
                        break;
                    else
                        ip = null;
                }

                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {

            e.printStackTrace();
        }
        return ip;
    }


二、AndroidMainifest.xml 添加权限

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET"/>

三、Unity 中调用

using UnityEngine;

/// <summary>
/// 通过IP,获取机器Mac地址
/// </summary>
public class GetWifiData 
{
    // 安卓的接口文档
    private AndroidJavaObject _androidJavaObject;

    public AndroidJavaObject mAndroidJavaObject {
        get {
            if (_androidJavaObject != null) {
                _androidJavaObject = new AndroidJavaObject("com.wifimacforarrow.pacificfuture.wifidataforarrow.WifiMgr");
            }

            return _androidJavaObject;
        }
    }
    /// <summary>
    /// 构造函数
    /// </summary>
    public GetWifiData() {

        _androidJavaObject = new AndroidJavaObject("com.wifimacforarrow.pacificfuture.wifidataforarrow.WifiMgr");
    }

    /// <summary>
    /// 获取设别的 Mac 地址
    /// </summary>
    /// <returns></returns>
    public string GetWifiMac() {

        
#if UNITY_EDITOR
        return "00:00:00:00:00:00";
#else
         return mAndroidJavaObject.CallStatic<string>("getMacAddress");
#endif

    }
}

 

 

 

 

=======================================================================================

=======================================================================================

Android Studio  WiFi 之 获取 WiFi 名称、IP、Mac(Android 7.0)

注意添加相关权限:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.text.format.Formatter;
import android.widget.TextView;

import java.net.NetworkInterface;
import java.net.SocketException;

public class MainActivity extends AppCompatActivity {

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 获取 textView 组件,把结果显示在UI上
        tv = findViewById(R.id.tv);
        tv.setText("ip "+getWifiIp() + " " +getWiFiName()+ " " +getWifiMacAddress());
    }


    /*
     * 获取 WIFI 的名称
     * */
    public String getWiFiName() {
        WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        if (wm != null) {
            WifiInfo winfo = wm.getConnectionInfo();
            if (winfo != null) {
                String s = winfo.getSSID();
                if (s.length() > 2 && s.charAt(0) == '"' && s.charAt(s.length() - 1) == '"') {
                    return s.substring(1, s.length() - 1);
                }
            }
        }
        return "Wifi 未获取到";
    }


    /*
     * 获取 WiFi 的 IP 地址
     * */
    public  String getWifiIp() {
        Context myContext = getApplicationContext();
        if (myContext == null) {
            throw new NullPointerException("上下文 context is null");
        }
        WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);
        if (isWifiEnabled()) {
            int ipAsInt = wifiMgr.getConnectionInfo().getIpAddress();
            String ip = Formatter.formatIpAddress(ipAsInt);
            if (ipAsInt == 0) {
                return "未能获取到IP地址";
            } else {
                return ip;
            }
        } else {
            return "WiFi 未连接";
        }
    }

    /*
     * 判断当前 WIFI 是否连接
     * */
    public  boolean isWifiEnabled() {
        Context myContext = getApplicationContext();
        if (myContext == null) {
            throw new NullPointerException("上下文 context is null");
        }
        WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);
        if (wifiMgr.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            ConnectivityManager connManager = (ConnectivityManager) myContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo wifiInfo = connManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            return wifiInfo.isConnected();
        } else {
            return false;
        }
    }

    /*
    * 获取 WiFi 的 Mac 地址
    *
    * */
    public String getWifiMacAddress(){

        Context myContext = getApplicationContext();
        if (myContext == null) {
            throw new NullPointerException("上下文 context is null");
        }
        WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);
        if (isWifiEnabled()) {

            // 该接口只能获得 02:00:00:00:00:02
            //String macAddress = wifiMgr.getConnectionInfo().getMacAddress();

            String macAddress = null;
            StringBuffer buf = new StringBuffer();
            NetworkInterface networkInterface = null;
            try {
                networkInterface = NetworkInterface.getByName("eth1");
                if (networkInterface == null) {
                    networkInterface = NetworkInterface.getByName("wlan0");
                }
                if (networkInterface == null) {
                    return "02:00:00:00:00:02";
                }
                byte[] addr = networkInterface.getHardwareAddress();


                for (byte b : addr) {
                    buf.append(String.format("%02X:", b));
                }
                if (buf.length() > 0) {
                    buf.deleteCharAt(buf.length() - 1);
                }
                macAddress = buf.toString();
            } catch (SocketException e) {
                e.printStackTrace();
                return "02:00:00:00:00:02";
            }

            return macAddress;


        } else {
            return "WiFi 未连接";
        }
    }




}

 

  • 7
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

仙魁XAN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值