Unity檢測網絡連接狀態

Unity中有自帶的判斷是否連接網絡的方法如下:

 if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            text1.text = "Unity自帶判斷,沒有聯網";
            Debug.Log("Unity自帶判斷,沒有聯網");
        }
        else if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork)
        {
            Debug.Log("Unity自帶,連接的移動網絡");
        }
        else if (Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork)
        {
            Debug.Log("Unity自帶,連接的wifi");
        }
        else
        {
            text1.text = "Unity自帶判斷,已經聯網";
            Debug.Log("Unity自帶判斷,已經聯網");
        }

但是這個方法在Unity編譯器中測試着是沒有問題的,但是將改程序打包成exe文件後就會發現,他無法判斷沒有聯網的狀態,

這時就需要使用C#中的方法去檢測是否聯網。

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class Test1 : MonoBehaviour {

    [DllImport("wininet")]
    private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);

    public Text text1;
    public Text text2;
    void Start () {
        StartCoroutine("delayPrint");
    }

    IEnumerator delayPrint()
    {
        yield return new WaitForSeconds(1f);


        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            text1.text = "Unity自帶判斷,沒有聯網";
            Debug.Log("Unity自帶判斷,沒有聯網");
        }
        else if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork)
        {
            text1.text = "Unity自帶,連接的移動網絡";
            Debug.Log("Unity自帶,連接的移動網絡");
        }
        else if (Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork)
        {
            text1.text = "Unity自帶,連接的wifi";
            Debug.Log("Unity自帶,連接的wifi");
        }
        else
        {
            text1.text = "Unity自帶判斷,已經聯網";
            Debug.Log("Unity自帶判斷,已經聯網");
        }

        if (IsConnectedInternet())
        {
            text2.text = "C#中判斷,聯網";
            Debug.Log("C#中判斷,聯網");
        }
        else
        {
            text2.text = "C#中判斷,沒有聯網";
            Debug.Log("C#中判斷,沒有聯網");
        }

        StartCoroutine("delayPrint");
    }

    /// <summary>
    /// C#判斷是否聯網
    /// </summary>
    /// <returns></returns>
    public bool IsConnectedInternet()
    {
        int i = 0;
        if (InternetGetConnectedState(out i,0))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}

這是在聯網狀態下的顯示:

這是在斷網情況下的顯示:

 

發佈了62 篇原創文章 · 獲贊 53 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章