How to detect remaining battery power through andr

2020-08-01 05:57发布

问题:

I am working on battery saver app. There I need to detect remaining battery. I have done following.

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) + "%");
    }
  };
}

But I am not getting battery value. Please help me

回答1:

You need to just change Intent.ACTION_BATTERY_LOW to Intent.ACTION_BATTERY_CHANGED. Rest code is okay. Let me know if you are other issue in this code.