How to detect remaining battery power through andr

2020-08-01 06:09发布

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条回答
戒情不戒烟
2楼-- · 2020-08-01 06:46

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.

查看更多
登录 后发表回答