BatteryManager stats not working on Android

走远了吗. 提交于 2019-12-11 11:26:15

问题


I am trying to get the batter level using a BroadCastReceiver:

int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);

I have added the following permissions to the AndroidManifest.xml:

<uses-permission android:name="android.permission.BATTERY_STATS" />

When I print the level and scale, I see the default value of 0. Are there additional settings to it?


回答1:


Calculating Battery Level in %:

You can find the current battery charge by extracting the current battery level and scale from the battery status intent as shown here:

int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

float batteryPct = level / (float)scale;

Implement BroadcastReceiver like this:

 BroadcastReceiver mybatteryReceiver= new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                int rawlevel = intent.getIntExtra("level", -1);
                int scale = intent.getIntExtra("scale", -1);
                int level = -1;
                if (rawlevel >= 0 && scale > 0) {
                    level = (rawlevel * 100) / scale;
                }
                Log.d("TEMP","Battery Level in % is:: " + level + "%");
            }
        };

Get a Code from here It is tried and tested. Works fine.

https://www.dropbox.com/s/1y6q5wu526ngz7t/BatteryStats.zip

Result of the code :




回答2:


No Permission Required for getting the battery charge status just use the following code in your broadcast receiver :-

int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);

This will result in battery Level :)



来源:https://stackoverflow.com/questions/12682841/batterymanager-stats-not-working-on-android

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