Android BatteryManager Returns only 1

给你一囗甜甜゛ 提交于 2019-12-07 17:55:44

问题


I am attempting to read the state of the Android battery when my repeating alarm broadcaster is called 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 that batteryPct = 1. Is there something I am missing here? I added the correct permissions based on the android Google page, but that doesn't seem to have helped.


回答1:


You are getting -1 for both level and scale. That 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 a receiver to 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 neet to device a receiver for this intent, just use the above mentioned way, whereever you want to use it.




回答2:


You might be getting -1 for both level and scale variable (the default value you specified), so try to print their values to make sure that the intent has those values set properly.

You should listen to ACTION_BATTERY_CHANGED to get battery level in Android



来源:https://stackoverflow.com/questions/14805318/android-batterymanager-returns-only-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!