Unity – Detect if Wifi is enabled on Android without plugin

Désolé, cet article est seulement disponible en English.

Sometimes you need to check the Wifi connection of the device on mobile for several reasons.

In order to get the permission to get the Wifi state you have to add this permission in the AndroidManifest.xml file:

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

Then use this code in your c# class:

AndroidJavaClass unityPlayerClass = new AndroidJavaClass ( "com.unity3d.player.UnityPlayer" );
AndroidJavaObject currentActivity = unityPlayerClass.GetStatic<AndroidJavaObject> ( "currentActivity" );
AndroidJavaClass contextClass = new AndroidJavaClass ( "android.content.Context" );
AndroidJavaObject context = currentActivity.Call<AndroidJavaObject> ( "getApplicationContext" );

string Context_WIFI_SERVICE = contextClass.GetStatic<string> ( "WIFI_SERVICE" );
AndroidJavaObject wifiService = context.Call<AndroidJavaObject> ( "getSystemService", Context_WIFI_SERVICE );
bool isWifiEnabled = wifiService.Call<bool> ( "isWifiEnabled" );