当电池电量低于10%时,如何禁用wifi?

时间:2013-06-26 14:45:07

标签: android android-wifi togglebutton batterylevel

我正在编写一个应用程序,当电池电量低于10%时,wifi连接(如果激活)将禁用。这是我想要的,但不是我能做的:)。我已经创建了一个切换按钮,当按下时,wifi停止,反之亦然,如果按下再次按下wifi,就会以这种方式打开:

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

    WifiManager wifiManager;
    if (on) {
      wifiManager(WifiManager) this.getSystemService(Context.WIFI_SERVICE);
      wifiManager.setWifiEnabled(false);
    } else {
      wifiManager(WifiManager) this.getSystemService(Context.WIFI_SERVICE);
      wifiManager.setWifiEnabled(tru);
    }
    }
通过这种方式,我获得了电池电量:

int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);

我想要的是像

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

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

有可能吗?感谢

1 个答案:

答案 0 :(得分:1)

如果要在单击按钮时检查电池电量:

public void getRisparmio(View view) {

   .....
   IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
   Intent batteryStatus = context.registerReceiver(null, ifilter);
   int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
   if (level<10){
       ......
   }
   .......
}

如果您想在电池电量不足时禁用wifi,可以使用此IntentFilter Intent.ACTION_BATTERY_LOW注册广播接收器。

public class BatteryReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {

           boolean batteryLow = intent.getAction().equals(Intent.ACTION_BATTERY_LOW);
           if (batteryLow){
                  ....
                   level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                   if (level<xx) {
                     //call your code
                     //wifiManager.setWifiEnabled(false);
                   }
           }
    }
}

onResume()的活动中,您可以注册广播接收器

BatteryReceiver receiver = new BatteryReceiver();
IntentFilter inf = new IntentFilter();
inf.addAction(BatteryReceiver); 
registerReceiver(receiver, inf);

请记得在onPause()中取消注册接收者。

否则您可以在Manifest.xml中注册

<reciever android:name=".BatteryReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BATTERY_LOW"/>
    </intent-filter>
</reciever>