我正在尝试使用BroadCastReceiver获取击球手级别:
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
我已将以下权限添加到AndroidManifest.xml:
<uses-permission android:name="android.permission.BATTERY_STATS" />
当我打印关卡和刻度时,我看到默认值为0.是否有其他设置?
答案 0 :(得分:3)
Calculating Battery Level in %:
您可以通过提取当前电池电量来查找当前电池电量,并根据电池状态意图进行缩放,如下所示:
int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level / (float)scale;
像这样实现BroadcastReceiver:
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 + "%");
}
};
从这里获取代码经过试用和测试。工作正常。
https://www.dropbox.com/s/1y6q5wu526ngz7t/BatteryStats.zip
代码结果:
答案 1 :(得分:0)
获取电池充电状态无需许可只需在广播接收器中使用以下代码: -
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
这将导致电池电量:)