Android BatteryManager only returns 1

I am trying to read the android battery status when an alarm repeater is triggered. I have the following setup:

public class RepeatingAlarm extends BroadcastReceiver {

    @Override       
    public void onReceive(Context context, Intent intent)
    {

            // Acquire the make of the device
            final String PhoneModel = android.os.Build.MODEL;
            final String AndroidVersion = android.os.Build.VERSION.RELEASE;

            // Grab the battery information
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            final float batteryPct = level / (float)scale; 
    }

}

      

But I don't understand why it is returning this batteryPct = 1

. Is there something I am missing here? I added the correct permissions based on the Google Android page, but it didn't seem to help.

+3


source to share


2 answers


You get -1

for level

and scale

. This is because you might be trying to broadcast ACTION_BATTERY_CHANGED

in the manifest.

ACTION_BATTERY_CHANGED

is a sticky intent and you cannot register it in the manifest. Try the following



 Intent i = new ContextWrapper(applicationContext).registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
 // now you can get the level and scale from this intent variable
int level = i.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = i.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

float battPct = level/(float)scale;

      

You would not want to use the device for this intent, just use the above method regardless of whether you want to use it.

+9


source


You can get -1 for both variables level

and scale

(the default value you specify), so try printing their values ​​to make sure you intent

have those values ​​correctly.



You must listen ACTION_BATTERY_CHANGED

to the battery level in Android

+2


source







All Articles