Enable/Disable Wifi on Android in Unity

前端 未结 1 803
名媛妹妹
名媛妹妹 2020-12-06 15:57

I am trying to enable or disable Wifi from Unity on my Android device. I tried to do the different things I found on the forum without success.

If I do:



        
1条回答
  •  星月不相逢
    2020-12-06 16:37

    According to Android Doc, setWifiEnabled takes bool as parameter and returns bool too.

    Your second code is almost close. You got the parameter right but failed to provide the return type. You put AndroidJavaObject as the return type instead of bool.

    In your second code, simply replace wifiManager.Call("setWifiEnabled", false); with wifiManager.Call("setWifiEnabled", false);.

    This should work, assuming that you have your permission in place. One advice to you is to put your code in a try catch clause. This will prevent some weird behavior if something is null or failed in your Android function calls.

    public bool setWifiEnabled(bool enabled)
    {
        using (AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic("currentActivity"))
        {
            try
            {
                using (var wifiManager = activity.Call("getSystemService", "wifi"))
                {
                    return wifiManager.Call("setWifiEnabled", enabled);
                }
            }
            catch (Exception e)
            {
            }
        }
        return false;
    }
    
    public bool isWifiEnabled()
    {
        using (AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic("currentActivity"))
        {
            try
            {
                using (var wifiManager = activity.Call("getSystemService", "wifi"))
                {
                    return wifiManager.Call("isWifiEnabled");
                }
            }
            catch (Exception e)
            {
    
            }
        }
        return false;
    }
    

    0 讨论(0)
提交回复
热议问题