Android的BatteryManager只返回1 [英] Android BatteryManager Returns only 1
问题描述
我试图阅读时,我重复报警广播叫我有以下安装了Android电池的状态:
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;
}
}
但我不明白为什么它返回了 batteryPct = 1
。是否有我丢失的东西吗?我加了基于Android谷歌页面上的正确的权限,但似乎并没有帮助。
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
为级别
和扩展
。
那是因为你可能会试图广播 ACTION_BATTERY_CHANGED
在清单。
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
是一个棘手的意图并不能在清单注册一个接收到它。请尝试以下
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;
您不会NEET到设备这种意图接收器,只需使用上述方法,等。无论您想使用它。
You would not neet to device a receiver for this intent, just use the above mentioned way, whereever you want to use it.
这篇关于Android的BatteryManager只返回1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!