如何使用ACTION_BATTERY_CHANGED?

时间:2019-02-09 14:10:29

标签: android arrays

如何使用ACTION_BATTERY_CHANGED来监视电池状态,如果它跌落到定义的值以下,您可以显示自定义的低电池对话吗? 有人给我一些示例代码。 当电池电量下降到30%时,会提供自定义的低电量对话

2 个答案:

答案 0 :(得分:1)

您必须使用BroadcastReceiver来获得所需的内容:

这是BroadcastReceiver类实现的示例

public class BatteryReceiver extends 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");
}
}
};

创建课程后,必须将BroadcastReceiver添加到AndroidManifest

<receiver android:name=".Receiver.BatteryReceiver ">
            <intent-filter>
            <action android:name="android.intent.action.ACTION_BATTERY_CHANGED"/>
            </intent-filter>
</receiver>

答案 1 :(得分:0)

在stackoverflow上,我们共享我们的代码并讨论问题,因此我们每个人都可以做得更好。如果您正在寻找这种东西,则可以简单地找到以下文档:

  

https://developer.android.com/training/monitoring-device-state/battery-monitoring

或在网络教程中。