How can I get a WifiManager Object inside of a Service?

10,418

Have you enabled the wifi on your device?

If your wifi is not enabled, it will show you UNINITIALZED output.

I just tried your code and it works fine with wifi enabled:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo w = wifi.getConnectionInfo();
Log.d(LOG_TAG, w.toString());

Logcat:

E/wpa_supplicant( 4337): wpa_driver_priv_driver_cmd failed
E/wpa_supplicant( 4337): wpa_driver_priv_driver_cmd failed
W/ActivityManager( 1332): Activity idle timeout for HistoryRecord{454624f8 com.xxx.xxx/.ui.SomeScreen}
D/SomeScreen( 4365): SSID: <none>, BSSID: <none>, MAC: 00:26:E8:B7:D2:E0, Supplicant state: DORMANT, RSSI: -200, Link speed: 54, Net ID: -1
Share:
10,418
Dennis
Author by

Dennis

Updated on June 26, 2022

Comments

  • Dennis
    Dennis almost 2 years

    I'm writing an app for Android that spawns a service that periodically checks the wifi state and changes it based on some conditions. My problem is that whenever I try to create a WifiManager object to check the state of the wifi (and perhaps control it), it gives me an uninitialized object. Here is the code:

    public class WifiCheckerService extends Service {
    
        // Service code and run() method
    
        private void checkWifi() {
            WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            System.out.println(wifi.getConnectionInfo());
            // Rest of code
        }
    }
    

    And here is the line in the log when it gets to this code.

    02-18 05:22:59.274: INFO/System.out(1170): SSID: <none>, BSSID: <none>, MAC: <none>, Supplicant state: UNINITIALIZED, RSSI: -200, Link speed: -1, Net ID: -1
    

    Obviously I'm not getting the system WifiManager object. I know it has something to do with the fact that I am in a service which is a thread, but I am still having trouble understanding the concept and a little explanation about why it's not working and how I can fix it would be greatly appreciated.

    (On a sort of unrelated note, I think an explanation would also explain why I can't use the line Toast.makeText(getBaseContext(), "Checking Wifi...", Toast.LENGTH_SHORT).show(); in the service)