Search code examples
androidonclickandroid-buttonbattery

How open battery usage by click in android


I want open the battery usage setting by click a button. The code is this:

Button btnusage = (Button)findViewById(R.id.batteryusage);
Button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        openOptionsBatt();
    }
});

And the method:

public openOptionsBatt(View v) {
    Intent intentBatteryUsage = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);        
    startActivity(intentBatteryUsage);
}

The application crash onCreate.. Why?


Solution

  • Try changing

    Button btnusage = (Button)findViewById(R.id.batteryusage);
    Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openOptionsBatt();
        }
    });
    

    to

    Button btnusage = (Button)findViewById(R.id.batteryusage);
    btnusage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openOptionsBatt();
        }
    });
    

    Note that in the second code snippet you're using btnusage, not Button. You want the OnClickListener to attach to your instance of Button not the class Button itself.

    Also, you're calling openOptionsBatt(); with passes 0 arguments, when your method public openOptionsBatt(View v) requires 1. I would change public openOptionsBatt(View v) to take 0 arguments. You're also missing the keyword void in your method signature.

    public void openOptionsBatt()