Search code examples
androidandroid-wifitogglebuttonbatterylevel

Crash onClick toggle button to disable wifi when battery less 20%


I've tryied this method to disable wifi on click of a toggle button when the battery is less 20% but the application crash on click:

public void getRisparmio(View view, Intent intent) {
    // is the toggle on?
    boolean on = ((ToggleButton) view).isChecked();

    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);

    WifiManager wifiManager;
    if (on && level<20) {
      wifiManager(WifiManager) this.getSystemService(Context.WIFI_SERVICE);
      wifiManager.setWifiEnabled(false);
    } else {
      wifiManager(WifiManager) this.getSystemService(Context.WIFI_SERVICE);
      wifiManager.setWifiEnabled(true);
    }
}

Any ideas?


Solution

  • It seems like you're missing a couple of = signs in your code. Try using:

    if (on && level<20) {
      wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
      wifiManager.setWifiEnabled(false);
    } else {
      wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
      wifiManager.setWifiEnabled(true);
    }