如何通过android编程检测电池剩余电量?

How to detect remaining battery power through android programming?

我正在开发省电应用程序。在那里我需要检测剩余电池。 我已经完成了。

public class HomeActivity extends Activity {
   TextView tv_battery;

  @Override
  public void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.main);
    tv_battery = (TextView) findViewById(R.id.tv_battery);


  }

  @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mBatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_LOW ));
    }
  private BroadcastReceiver mBatteryReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context ctxt, Intent intent) {
      int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
      tv_battery.setText("Remaining Battery : "+String.valueOf(level) + "%");
    }
  };
}

但我没有获取电池电量。请帮助我

您只需将 Intent.ACTION_BATTERY_LOW 更改为 Intent.ACTION_BATTERY_CHANGED。休息代码没问题。如果您在此代码中遇到其他问题,请告诉我。