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 en_netInterface = NetworkInterface
                    .getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {// 是否还有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface
                        .nextElement();// 得到下一个元素
                Enumeration 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 添加权限

    
    
    

三、Unity 中调用

using UnityEngine;

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

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

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

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

    /// 
    /// 获取设别的 Mac 地址
    /// 
    /// 
    public string GetWifiMac() {

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

    }
}

 

 

 

 

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

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

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

注意添加相关权限:

 
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 未连接";
        }
    }




}

 

Android Studio WiFi 之 获取 WiFi 名称、IP、Mac_第1张图片

你可能感兴趣的:(Unity,Android,交互,Android,Unity,WiFi)