BatteryManager的统计数据与不工作在Android [英] BatteryManager stats not working on Android

查看:291
本文介绍了BatteryManager的统计数据与不工作在Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个BroadcastReceiver来获得连击级别:

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);

我添加了以下权限的Andr​​oidManifest.xml:

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

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

当我打印水平和规模,我看到的默认值0。是否给它还有额外的设置?

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

推荐答案

<一个href=\"http://developer.android.com/training/monitoring-device-state/battery-monitoring.html#CurrentLevel\"相对=nofollow>在计算%电池电量:

您可以找到提取电池状态的意图目前的电池水平和规模当前电池电量如下所示:

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;

实现BroadcastReceiver的是这样的:

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 + "%");
            }
        };

获取code从这里它是经得起考验的。工作正常。

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

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

在code的结果:

Result of the code :

这篇关于BatteryManager的统计数据与不工作在Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆