在Android中获取电池电量和状态


109

如何获得电池电量和状态(插入,放电,充电等)?我研究了开发人员文档,并找到了BatteryManager类。但是它不包含任何方法,仅包含常量。我什至如何使用它?


经过更多研究后,我找到了BatteryManager.EXTRA_LEVEL。
Mohit Deshpande'7

检查此方法以在此处获取电池百分比freakyjolly.com/android-useful-methods-and-functions/#5method
Code Spy

Answers:


124

是一个代码示例,解释了如何获取电池信息。

综上所述,该ACTION_BATTERY_CHANGED意图的广播接收器是动态设置的,因为只有通过使用显式注册它才能通过清单中声明的​​组件来接收它Context.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, 0);
      batteryTxt.setText(String.valueOf(level) + "%");
    }
  };

  @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
关于Intent.ACTION_BATTERY_CHANGED:这是一个粘性广播,其中包含充电状态,电量和有关电池的其他信息。您不能通过清单中声明的​​组件来接收此消息,只能通过向Context.registerReceiver()进行显式注册来实现。
Android类

2
@classAndroid好吧,是的,答案中有明确说明。
SirDarius,2015年

是的@SirDarius,只是让其他人知道。我首先对您的答案进行了投票,并在找到答案后发表了此评论。:)
类Android

13
不要忘记在onPause或onDestroy上取消注册接收器。
Dave Doga Oz 2015年

先生,为什么无法使用新的Keywork使电池管理器正常安装,为什么?
subhashchandru

102

从API 21开始,就可以使用以下命令获取当前电池电量百分比:

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

65

根据官方android docs,您可以在Helper或Util类中使用此方法来获取当前电池电量百分比:

public static int getBatteryPercentage(Context context) {

    if (Build.VERSION.SDK_INT >= 21) {

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

    } else {

         IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
         Intent batteryStatus = context.registerReceiver(null, iFilter);

         int level = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
         int scale = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;

         double batteryPct = level / (double) scale;

         return (int) (batteryPct * 100);
   }
}

官方文档中的一个错误,您必须使用double而不是float int level = batteryStatus!= null?batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL,-1):-1; int scale = batteryStatus!=空吗?batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE,-1):-1; double batteryPct =(double)level /(double)scale; int百分比=(int)(batteryPct * 100D);
user2212515 '18

2
@ user2212515,您介意根据官方文档编辑我的答案吗?
blueware

@Ryan,我编辑了答案以支持android v21及更高版本。请检查一下。
blueware

14

您无需注册实际的BroadcastReceiver,因为Android的BatteryManager使用粘性Intent:

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, ifilter);

int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

float batteryPct = level / (float)scale;

return (int)(batteryPct*100);

这是来自https://developer.android.com/training/monitoring-device-state/battery-monitoring.html上的官方文档。


7

您可以使用此百分比收取剩余费用。

private void batteryLevel() {
        BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                context.unregisterReceiver(this);
                int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                int level = -1;
                if (rawlevel >= 0 && scale > 0) {
                    level = (rawlevel * 100) / scale;
                }
                batterLevel.setText("Battery Level Remaining: " + level + "%");
            }
        };
        IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryLevelReceiver, batteryLevelFilter);
    }

5

尝试此功能无需许可或任何收款人

void getBattery_percentage()
{
      IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
      Intent batteryStatus = getApplicationContext().registerReceiver(null, ifilter);
      int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
      int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
      float batteryPct = level / (float)scale;
      float p = batteryPct * 100;

      Log.d("Battery percentage",String.valueOf(Math.round(p)));
  }

4

要检查电池百分比,我们使用BatteryManager,以下方法将返回电池百分比。

链接

public static float getBatteryLevel(Context context, Intent intent) {
    Intent batteryStatus = context.registerReceiver(null,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int batteryLevel = -1;
    int batteryScale = 1;
    if (batteryStatus != null) {
        batteryLevel = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, batteryLevel);
        batteryScale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, batteryScale);
    }
    return batteryLevel / (float) batteryScale * 100;
}

嘿,我用了它,有时结果是89有时是00.89,其移动小数点是怎么回事
Pemba Tamang

1
private void batteryLevel() {
        BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                context.unregisterReceiver(this);
                int rawlevel = intent.getIntExtra("level", -1);
                int scale = intent.getIntExtra("scale", -1);
                int level = -1;
                if (rawlevel >= 0 && scale > 0) {
                    level = (rawlevel * 100) / scale;
                }
                mBtn.setText("Battery Level Remaining: " + level + "%");
            }
        };
        IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryLevelReceiver, batteryLevelFilter);
    }

1

官方文档中的一个错误,您必须使用double而不是float。因为0.53F * 100F = 52F

int level = batteryStatus != null ? 
batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1; int scale = 
batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1; 
double batteryPct = (double) level / (double) scale; int percent = (int) (batteryPct * 100D);

这不是0.53F-> 52F错误,是由于将最终值强制转换为int(因此从中删除了任何十进制0.x值)而不是使用Math.round()引起的?
Robyer

0

其他答案没有提到如何访问电池状态(是否变废)。

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                     status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.