如何在Android背景下监控电池电量?

时间:2013-09-24 23:33:26

标签: android background broadcastreceiver intentservice battery

因此,对于我的应用程序,我想监控电池电量,即使我的应用程序已关闭,然后在电池电量低于某个百分比时发送通知。我知道如何创建像this这样的后台服务,但我不确定如何使用它来监控电池电量。我会在Manifest文件中注册BroadcastReceiver,还是应该动态地执行?另外,我担心在收到第一次更新后,操作系统会终止BroadcastReceiver。

1 个答案:

答案 0 :(得分:6)

你必须动态注册它。

在服务中这样做可能是一个不错的选择。这就是我用过的:

this.registerReceiver(this.mBatInfoReceiver, 
                  new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

...

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context arg0, Intent intent) {
      // TODO Auto-generated method stub
        //this will give you battery current status

    try{
      int level = intent.getIntExtra("level", 0);
      int temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
      int voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
      int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

      String BStatus = "No Data";
      if (status == BatteryManager.BATTERY_STATUS_CHARGING){BStatus = "Charging";}
      if (status == BatteryManager.BATTERY_STATUS_DISCHARGING){BStatus = "Discharging";}
      if (status == BatteryManager.BATTERY_STATUS_FULL){BStatus = "Full";}
      if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING){BStatus = "Not Charging";}
      if (status == BatteryManager.BATTERY_STATUS_UNKNOWN){BStatus = "Unknown";}

      int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
      String BattPowerSource = "No Data";
      if (chargePlug == BatteryManager.BATTERY_PLUGGED_AC){BattPowerSource = "AC";}
      if (chargePlug == BatteryManager.BATTERY_PLUGGED_USB){BattPowerSource = "USB";}

      String BattLevel = String.valueOf(level);

      int BHealth = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, -1);
      String BatteryHealth = "No Data";
      if (BHealth == BatteryManager.BATTERY_HEALTH_COLD){BatteryHealth = "Cold";}
      if (BHealth == BatteryManager.BATTERY_HEALTH_DEAD){BatteryHealth = "Dead";}
      if (BHealth == BatteryManager.BATTERY_HEALTH_GOOD){BatteryHealth = "Good";}
      if (BHealth == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){BatteryHealth = "Over-Voltage";}
      if (BHealth == BatteryManager.BATTERY_HEALTH_OVERHEAT){BatteryHealth = "Overheat";}
      if (BHealth == BatteryManager.BATTERY_HEALTH_UNKNOWN){BatteryHealth = "Unknown";}
      if (BHealth == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){BatteryHealth = "Unspecified Failure";}

      //Do whatever with the data here


    } catch (Exception e){
        Log.v(TAG, "Battery Info Error");
    }
    }
  };