在安卓系统中获取电池电量和状态

2022-08-31 08:28:34

如何获取电池电量和状态(接通电源、放电、充电等)?我研究了开发人员文档,发现了一个BatteryManager类。但它不包含任何方法,只包含常量。我该如何使用它?


答案 1

下面是一个代码示例,说明如何获取电池信息。

总而言之,意图的广播接收器是动态设置的,因为它不能通过清单中声明的组件接收,只能通过显式注册它来接收。ACTION_BATTERY_CHANGEDContext.registerReceiver()

public class Main extends Activity {
  private TextView batteryTxt;
  private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context ctxt, Intent intent) {
      int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
      int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
      float batteryPct = level * 100 / (float)scale;
      batteryTxt.setText(String.valueOf(batteryPct) + "%");
    }
  };

  @Override
  public void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.main);
    batteryTxt = (TextView) this.findViewById(R.id.batteryTxt);
    this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
  }
}

答案 2

由于可以使用以下内容以百分比形式获取当前电池电量:SDK 21LOLLIPOP

BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

阅读电池管理器|安卓开发者 - BATTERY_PROPERTY_CAPACITY


推荐