Unity Android 搜索附近WiFi与连接

此文章为转载文章,但是中间有略微修改,其他都是全文拷贝过来,原文链接在文章最后(如若转载请说明原文链接,谢谢!原创不容易,大家都理解下)

一:wifi涉及到的权限

    允许程序改变网络连接状态
    允许程序改变Wi-Fi连接状态
    获取网络信息状态
    获取当前WiFi接入的状态以及WLAN热点的信息
    允许使用PowerManager的 WakeLocks保持进程在休眠时从屏幕消失
   
       访问网络连接
二:android系统相关wifi类
WifiManager
wifi管理的API,包括wifi的扫描,建立连接,配置,断开连接等等。
wifiManager.isWifiEnabled();//判断是否开启
wifiManager.setWifiEnabled(true);//设置开启关闭
注意,调用setWifiEnabled后,系统进行wifi模块的开启需要一定时间,此时通过wifiManager.getWifiState()获取的状态来判断是否完成。

WifiManager.WIFI_STATE_DISABLED : WIFI网卡不可用(1)

WifiManager.WIFI_STATE_DISABLING : WIFI网卡正在关闭(0)

WifiManager.WIFI_STATE_ENABLED : WIFI网卡可用(3)

WifiManager.WIFI_STATE_ENABLING : WIFI网正在打开(2) (WIFI启动需要一段时间)

WifiManager.WIFI_STATE_UNKNOWN  : 未知网卡状态
具体参考:http://developer.android.com/reference/android/net/wifi/WifiManager.html
WifiInfo
描述已经建立连接的wifi信息。包括ip,mac地址,连接速度
具体参考:http://developer.android.com/reference/android/net/wifi/WifiInfo.html
ConnectivityManager
监控网络连接,当网络连接发生变化时返送广播,当一个网络请求连接失败的时候他会自动转到其他可连接网络等等
获取方式Context.getSystemService(Context.CONNECTIVITY_SERVICE)
具体参考:https://developer.android.com/reference/android/net/ConnectivityManager.html
WifiLock (WifiManager.WifiLock)
它是wifiManager里面的一个类。服务于WifiManager。当无线wifi有一段事件没用的时候系统可能会自动关闭,WifiLock 可以让无线wifi保持唤醒状态
具体参考:https://developer.android.com/reference/android/net/wifi/WifiManager.WifiLock.html
ScanResult(包是:android.net.wifi。不要import错包,因为蓝牙包中android.blutooth.le也有这个类)
开启扫描后搜索到的wifi热点的信息,包括SSID,Capbilities,frequency,level等等
具体介绍参考:http://developer.android.com/reference/android/net/wifi/ScanResult.html
WifiConfiguration
描述wifi的连接信息,包括SSID,SSID隐藏,password等等设置。
具体介绍参考:https://developer.android.com/reference/android/net/wifi/WifiConfiguration.html

二:android工程(报名也要修改成unity工程包名字)
1:PTWifiConnect

package com.risenb.wifiproject;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import java.util.List;
public class PTWifiConnect {
    WifiManager wifiManager;

    //wifi连接类型
    public enum WifiCipherType {
        WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
    }

    public PTWifiConnect(WifiManager wifiManager) {
        this.wifiManager = wifiManager;
    }

    private boolean openWifi() {
        boolean bRet = true;
        if (!wifiManager.isWifiEnabled()) {
            bRet = wifiManager.setWifiEnabled(true);
        }
        return bRet;
    }

    public boolean connect(String SSID, String Password, WifiCipherType Type) {
        if (!this.openWifi()) {
            return false;
        }
        while (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
            try {
                Thread.currentThread();
                Thread.sleep(100);
            } catch (InterruptedException ie) {
            }
        }
        WifiConfiguration wifiConfig = this.createWifiInfo(SSID, Password, Type);
        //
        if (wifiConfig == null) {
            return false;
        }
        WifiConfiguration tempConfig = this.isExsits(SSID);
        if (tempConfig != null) {
            wifiManager.removeNetwork(tempConfig.networkId);
        }
        int netID = wifiManager.addNetwork(wifiConfig);
        boolean bRet = wifiManager.enableNetwork(netID, false);
        return bRet;
    }

    private WifiConfiguration isExsits(String SSID) {
        List existingConfigs = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }

    private WifiConfiguration createWifiInfo(String SSID, String Password, WifiCipherType Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";

        WifiConfiguration tempConfig = this.IsExsits(SSID);
        if(tempConfig != null) {
            wifiManager.removeNetwork(tempConfig.networkId);
        }

        if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == WifiCipherType.WIFICIPHER_WEP) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == WifiCipherType.WIFICIPHER_WPA) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            //config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

            config.status = WifiConfiguration.Status.ENABLED;
        } else {
            return null;
        }
        return config;
    }
    private WifiConfiguration IsExsits(String SSID)
    {
        List existingConfigs = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs)
        {
            if (existingConfig.SSID.equals("\""+SSID+"\""))
            {
                return existingConfig;
            }
        }
        return null;
    }
}


2:PTWifiAdministrator

package com.risenb.wifiproject;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.widget.Toast;
import com.risenb.wifiproject.PTWifiConnect.WifiCipherType;
import java.net.Inet4Address;
import java.util.ArrayList;
import java.util.List;

public class PTWifiAdministrator {
    private WifiManager wifiManager; //wifi管理api
    private WifiInfo wifiInfo; //具体wifi数据api
    private List scanResultList; //wifi扫描结果
    private List wifiConfigurationList;

    WifiLock wifiLock;
    public PTWifiAdministrator(Context context)
    {
        wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager!=null)
            wifiInfo = wifiManager.getConnectionInfo();
    }
    //获取wifi状态
    public int GetWifiState()
    {
        return wifiManager.getWifiState();
    }
    // 创建一个WifiLock
    public void CreateWifiLock()
    {
        wifiLock = wifiManager.createWifiLock("PTWifiLock");
    }
    public void AcquireWifiLock()
    {
        wifiLock.acquire();
    }
    // 得到配置好的网络
    public List GetWifiConfiguration()
    {
        return wifiConfigurationList;
    }
    // 指定配置好的网络进行连接
    public boolean ConnectConfiguration(int index) {
        if (wifiConfigurationList == null || index > wifiConfigurationList.size()) {
            return false;
        }else{
            return wifiManager.enableNetwork(wifiConfigurationList.get(index).networkId, true);
        }
    }
    //开始扫描周为wifi或者热点
    public void StartScanWifi() {
        wifiManager.startScan();
        List results = wifiManager.getScanResults();
        //scanResultList = wifiManager.getScanResults();
        wifiConfigurationList = wifiManager.getConfiguredNetworks();
        if (results == null) {
//            if (wifiManager.getWifiState() == 3) {
//                Toast.makeText(context, "当前区域没有无线网络", Toast.LENGTH_SHORT).show();
//            } else if (wifiManager.getWifiState() == 2) {
//                Toast.makeText(context, "wifi正在开启,请稍后扫描", Toast.LENGTH_SHORT).show();
//            } else {
//                Toast.makeText(context, "WiFi没有开启", Toast.LENGTH_SHORT).show();
//            }
        } else {
            scanResultList = new ArrayList();
            for (ScanResult result : results) {
                if (result.SSID == null || result.SSID.length() == 0 || result.capabilities.contains("[IBSS]")) {
                    continue;
                }
                boolean found = false;
                for (ScanResult item : scanResultList) {
                    if (item.SSID.equals(result.SSID) && item.capabilities.equals(result.capabilities)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    scanResultList.add(result);
                }
            }
        }
    }
    // 得到网络列表
    public List GetScanResults()
    {
        return scanResultList;
    }
    //预览扫描到的wifi
    public String LookUpScan()
    {
        StringBuffer sb = new StringBuffer();

        for(int i=0;i existingConfigs = wifiManager.getConfiguredNetworks();
        for(WifiConfiguration temp:existingConfigs) {
            if (temp.SSID.equals("\"" + SSID + "\"")) {
                return temp;
            }
        }
        return null;
    }
    //生成WifiConfiguration对象 给连接wifi用
    private WifiConfiguration CreateWifiConfiguration(String SSID, String Password,PTWifiConnect.WifiCipherType Type) {
        WifiConfiguration wifiConfiguration = new WifiConfiguration();
        wifiConfiguration.allowedAuthAlgorithms.clear();
        wifiConfiguration.allowedGroupCiphers.clear();
        wifiConfiguration.allowedKeyManagement.clear();
        wifiConfiguration.allowedPairwiseCiphers.clear();
        wifiConfiguration.allowedProtocols.clear();
        wifiConfiguration.SSID = "\"" + SSID + "\"";
        if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
            wifiConfiguration.wepKeys[0] = "";
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            wifiConfiguration.wepTxKeyIndex = 0;
        } else if (Type == WifiCipherType.WIFICIPHER_WEP) {
            wifiConfiguration.preSharedKey = "\"" + Password + "\"";
            wifiConfiguration.hiddenSSID = true;
            wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            wifiConfiguration.wepTxKeyIndex = 0;
        } else if (Type == WifiCipherType.WIFICIPHER_WPA) {
            wifiConfiguration.preSharedKey = "\"" + Password + "\"";
            wifiConfiguration.hiddenSSID = true;
            wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        } else {
            return null;
        }
        return wifiConfiguration;
    }
    public String ipIntToString(int ip) {
        try {

            byte[] bytes = new byte[4];
            bytes[0] = (byte) (0xff & ip);
            bytes[1] = (byte) ((0xff00 & ip) >> 8);
            bytes[2] = (byte) ((0xff0000 & ip) >> 16);
            bytes[3] = (byte) ((0xff000000 & ip) >> 24);
            return Inet4Address.getByAddress(bytes).getHostAddress();
        } catch (Exception e) {
            return "";
        }
    }
    public int getConnNetId() {
        // result.SSID;
        wifiInfo = wifiManager.getConnectionInfo();
        return wifiInfo.getNetworkId();
    }
    public boolean connectSpecificAP(ScanResult scan,String password)
    {
        List list = wifiManager.getConfiguredNetworks();
        boolean networkInSupplicant = false;
        boolean connectResult = false;
        wifiManager.disconnect();
        for (WifiConfiguration w : list) {
            // String str = convertToQuotedString(info.ssid);
            if (w.BSSID != null && w.BSSID.equals(scan.BSSID)) {
                connectResult = wifiManager.enableNetwork(w.networkId, true);
                // mWifiManager.saveConfiguration();
                networkInSupplicant = true;
                break;
            }
        }
        if (!networkInSupplicant) {
            WifiConfiguration config = CreateWifiInfo(scan, password);
            connectResult = addNetwork(config);
        }
        return connectResult;
    }
    public boolean addNetwork(WifiConfiguration wcg) {
        if (wcg == null) {
            return false;
        }
        //receiverDhcp = new ReceiverDhcp(ctx, mWifiManager, this, wlanHandler);
        // ctx.registerReceiver(receiverDhcp, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
        int wcgID = wifiManager.addNetwork(wcg);
        boolean b = wifiManager.enableNetwork(wcgID, true);
        wifiManager.saveConfiguration();
        System.out.println(b);
        return b;
    }
    public WifiConfiguration CreateWifiInfo(ScanResult scan, String Password)
    {
        WifiConfiguration config = new WifiConfiguration();
        config.hiddenSSID = false;
        config.status = WifiConfiguration.Status.ENABLED;
        if (scan.capabilities.contains("WEP")) {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.SSID = "\"" + scan.SSID + "\"";
            config.wepTxKeyIndex = 0;
            config.wepKeys[0] = Password;
            // config.preSharedKey = "\"" + SHARED_KEY + "\"";
        } else if (scan.capabilities.contains("PSK")) {
            config.SSID = "\"" + scan.SSID + "\"";
            config.preSharedKey = "\"" + Password + "\"";
        } else if (scan.capabilities.contains("EAP")) {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.SSID = "\"" + scan.SSID + "\"";
            config.preSharedKey = "\"" + Password + "\"";
        } else {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.SSID = "\"" + scan.SSID + "\"";
            // config.BSSID = info.mac;
            config.preSharedKey = null;
        }
        return config;
    }

}


3:MainActivity(这个activity主要是给unity交互用的,如果你懂android开发,换成自己的activity就行,把这个类的方法考进去就行)

package com.risenb.wifiproject;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

public class MainActivity extends UnityPlayerActivity {
    public PTWifiAdministrator ptWifiAdministrator;
    private String unitygameobjectName = "AndroidBluetooth"; //Unity 中对应挂脚本对象的名称
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ptWifiAdministrator = new PTWifiAdministrator(this);
        //setContentView(R.layout.activity_main);
    }
    //***********WIFI************
    //打开wifi
    public void OpenWifi()
    {
        ptWifiAdministrator.OpenWifi();
    }
    //获取wwifi状态
    public boolean GetWifiState() {
        int state_id = ptWifiAdministrator.GetWifiState();
        UnityPlayer.UnitySendMessage(unitygameobjectName, "PTUnityWifiReceiveState", "state:" + state_id);
        return state_id == 3;
    }
    android.net.wifi.ScanResult scanResult;
    //连接wifi
    public void ConnetWifi(int number,String password)
    {
        scanResult = ptWifiAdministrator.GetScanResults().get(number);
        ptWifiAdministrator.connectSpecificAP(scanResult,password);
    }
    //是否连接成功
    public boolean IsConnect()
    {
        boolean b = ptWifiAdministrator.IsConnect(scanResult);
        if(b)scanResult = null;
        return b;
    }
    //扫描
    public void WifiInit() {
        if (ptWifiAdministrator == null)
            ptWifiAdministrator = new PTWifiAdministrator(this);
        ptWifiAdministrator.StartScanWifi();
        //ptWifiAdministrator.GetScanResults();

        String ScanList = ptWifiAdministrator.LookUpScan();
        UnityPlayer.UnitySendMessage(unitygameobjectName, "PTUnityWifiReceive", ScanList);
    }
}

4:androidManifest.xml在unity中这样配置

    package="com.yxh.wifi"
    android:versionCode="1"
    android:versionName="1.0" >


            android:minSdkVersion="8"
        android:targetSdkVersion="21" />
 
 
 
 
 
 


 
            android:allowBackup="true"
        android:icon="@drawable/app_icon"
        android:label="@string/app_name"
        >
                    android:name=".MainActivity"
            android:label="@string/app_name" >
           
               


               
           
       
   



5:unity这边与android交互的类PTUnityWifiObject

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PTUnityWifiObject : MonoBehaviour {
    public static PTUnityWifiObject instance;
    public Button btn;
    public Button btn1;
    private AndroidJavaClass aJC;
    private AndroidJavaObject aJO;
    // Use this for initialization
    void Start () {
        instance = this;
        btn.onClick.AddListener(OpenWifi);
        btn1.onClick.AddListener(SearchWifi);
    }
    public void OpenWifi()
    {

        if (aJO == null)
        {
            aJC = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            aJO = aJC.GetStatic("currentActivity");
        }
        if (aJO != null)
        {
            //PTWifi.tempT += "OpenWifi";
            aJO.Call("OpenWifi");
            StartCoroutine(GetOpenIsOk());
        }
    }
    IEnumerator GetOpenIsOk()
    {
        yield return new WaitForSeconds(1f);
        if (aJO.Call("GetWifiState"))
        {
            //wifi开启成功
            SearchWifi();
        }
        else
        {
            StartCoroutine(GetOpenIsOk());
        }
    }
    public void SearchWifi()
    {
        if (aJO == null)
        {
            aJC = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            aJO = aJC.GetStatic("currentActivity");
        }
        if (aJO != null)
        {
            //Debug.Log("This is WifiInit");
            aJO.Call("WifiInit");
        }
    }
    //连接wifi
    public void ConnectWifi(int number,string password)
    {
        if (aJO != null)
        {
            aJO.Call("ConnetWifi", new object[] { number, password });
        }
        StartCoroutine(WaitConnect(number));
    }
    IEnumerator WaitConnect(int index)
    {
        yield return new WaitForSeconds(0.5f);
        if (aJO != null)
        {
            if (aJO.Call("IsConnect"))
            {
                SearchWifi();
            }
            else
            {
                StartCoroutine(WaitConnect(index));
            }
        }
    }
    // Update is called once per frame
    void Update () {}
    void OnDestory()
    {
        instance = null;
    }
    public Text text;
    ///


    /// Android 返回无线列表SSID
    ///

    public void PTUnityWifiReceive(string str)
    {
        Debug.Log(str);
        WIFIStateManage.Instance.ShowWifiList(str);
    }
    ///
    /// Android 返回状态
    ///

    public void PTUnityWifiReceiveState(string str)
    {
        Debug.Log("PTUnityWifiReceiveState:" + str);
    }
}

6.unity 创建WiFi列表与赋值WiFi状态类 WIFIStateManage

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class WIFIStateManage : MonoSingleton
{
    public GameObject wifiPrefab;       //列表预设体
    public Transform wifiParentTrans;   //放WiFi列表位置
    private int maxVideoCount = 0;      //当前所拥有数量
    private int nowVideoCount = 0;      //当下所需数量


    public GameObject inputPasswordObj; //输入密码面板
    public int index = 0;               //选择WiFi的Index
    private string inputPassword = "";
    public InputField passwordInputField;
    public Button cancelBtn;            //取消
    public Button confirmBtn;           //确定
    public Dictionary m_WifiPropertManage = new Dictionary(); //安卓返回数据
    void Start()
    {
        cancelBtn.onClick.AddListener(CancelBtnOnClick);
        confirmBtn.onClick.AddListener(ConfirmBtnClick);
    }
    ///


    /// 创建WiFi列表
    ///

    ///
    public void ShowWifiList(string str)
    {
        string[] data = str.Split(';');
        nowVideoCount = data.Length - 1;
        maxVideoCount = wifiParentTrans.childCount;
        m_WifiPropertManage.Clear();
        //关闭之前创建出的列表预设体
        for (int child = 0; child < wifiParentTrans.childCount; child++)
        {
            GameObject wifiobj = wifiParentTrans.transform.GetChild(child).gameObject;
            wifiobj.SetActive(false);
        }

        int i = 0;
        //有就赋值,没有创建
        foreach (string wifistr in data)
        {
            if (i < nowVideoCount)
            {
                string[] wifi = wifistr.Split(':');
                WifiPropertyManage wifipro = new WifiPropertyManage();
                wifipro.WifiIndex = int.Parse(wifi[0]);
                wifipro.WifiSSID = wifi[1];
                wifipro.WifiLevel = int.Parse(wifi[2]);
                wifipro.WifiCapabilities = wifi[3];
                wifipro._wifiIsConnectStr = wifi[4];
                m_WifiPropertManage.Add(wifipro.WifiIndex, wifipro);

                if (nowVideoCount > maxVideoCount)
                {
                    GameObject obj = GameObject.Instantiate(wifiPrefab);
                    obj.name = "wifi" + maxVideoCount;
                    obj.transform.SetParent(wifiParentTrans);
                    obj.transform.localPosition = new Vector3(0, 0, 0);
                    obj.transform.localScale = new Vector3(1, 1, 1);
                    WifiListData wifilist = obj.GetComponent();
                    wifilist.index = int.Parse(wifi[0]);
                    wifilist.SSID = wifi[1];
                    wifilist.level = int.Parse(wifi[2]);
                    wifilist.init();
                    maxVideoCount++;
                }
                else
                {
                    GameObject wifiobj = wifiParentTrans.transform.GetChild(i).gameObject;
                    WifiListData wifilist = wifiobj.GetComponent();
                    wifilist.index = int.Parse(wifi[0]);
                    wifilist.SSID = wifi[1];
                    wifilist.init();
                    wifiobj.SetActive(true);
                }
            }
            i++;
        }
    }
    ///


    /// 取消输入密码事件
    ///

    private void CancelBtnOnClick()
    {
        inputPasswordObj.SetActive(false);
        passwordInputField.text = "";
    }
    ///
    /// 确定连接按钮事件
    ///

    public void ConfirmBtnClick()
    {
        inputPassword = passwordInputField.text;


        if (inputPassword.Length >= 8)
        {
            PTUnityWifiObject.instance.ConnectWifi(index, inputPassword);
            CancelBtnOnClick();
        }
        else
        {
            Debug.Log("密码位数不少于8位");
        }

    }
}
///


/// WiFi属性
///

public class WifiPropertyManage
{
    private int _wifiIndex;
    ///
    /// android 返回 WiFi index
    ///

    public int WifiIndex
    {
        get { return _wifiIndex; }
        set { _wifiIndex = value; }
    }

    private string _wifiSSID;
    ///


    /// android 返回 WiFi SSID
    ///

    public string WifiSSID
    {
        get { return _wifiSSID; }
        set { _wifiSSID = value; }
    }

    private int _wifiLevel;
    ///


    /// android 返回 WIFI 信号
    ///

    public int WifiLevel
    {
        get { return _wifiLevel; }
        set { _wifiLevel = value; }
    }

    public string _wifiIsConnectStr;
    ///


    /// WiFi是否连接 0-未连接 1-连接
    ///

    public bool WifiIsConnect
    {
        get{
            bool _wifiIsConnect = false;
            if(_wifiIsConnectStr == "1")
            {
                _wifiIsConnect = true;
            }
            return _wifiIsConnect;
        }
        //set { _wifiIsConnect = value; }
    }

    private string _wifiCapabilities;
    ///


    /// WiFi安全
    ///

    public string WifiCapabilities
    {
        get { return _wifiCapabilities; }
        set { _wifiCapabilities = value; }
    }
}

有些手机可能扫描不出周围WiFi的信息,我在网上找了下资料发现AndroidManifest.xml中缺少2个权限,加上就可以扫描出WiFi了

   
   

源码(Android,unity)下载地址:https://download.csdn.net/download/mrbaiyuntao/10786812

原文:https://blog.csdn.net/y90o08u28/article/details/51831052


 

你可能感兴趣的:(WiFi,转载)