Search code examples
androidandroid-wifi

how do I turn on the WiFi scanner?


I have tried to get the current state of the WiFi scanner using the code:

ConnectivityManager manager = (ConnectivityManager)getSystemService(MainActivity.CONNECTIVITY_SERVICE);

 State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

Unfortunately the second line is causing my app to crash when I run it. commenting the line allows the app to execute without any problems. This part is very important for this app.I cannot proceed with the remaining code without it. It crashes on an Emulator(Android ver: 4.2.2 API level 17) and also on an Xperia running ICS 4.0.4 (API level 15). The minimum required API level is set to 8. The code has no errors.

EDIT: What works is: Alternate code:

final WifiManager wifiManagerI = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

boolean wifiEnabledI = wifiManagerI.isWifiEnabled();


Solution

  • Without a log, my wild guess is you forgot to add a permission.

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

    EDIT: It ended up this code fixed the issue.

    final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 
    boolean wifiEnabled =   wifiManager.isWifiEnabled();