在我的应用程序中,我想在电池电量不足时做一些事情。当电池电量不足时,机器人会发出ACTION_BATTERY_LOW
并且当电池再次达到其良好状态时,它会触发意图ACTION_BATTERY_OKAY
。所以,我有三个问题:
1.安卓实际触发的电池百分比是ACTION_BATTERY_LOW
?
2.如果电池电量更低,它会反复触发同一事件吗?
3.我们可以配置android会触发ACTION_BATTERY_LOW
意图的电池百分比吗?
我更关心第三点。
答案 0 :(得分:11)
不,您无法设置何时发送ACTION_BATTERY_LOW阈值。这是由Android ROM指定的系统级意图。以下是在电池服务中设置值的代码:
mLowBatteryWarningLevel = mContext.getResources().getInteger(
com.android.internal.R.integer.config_lowBatteryWarningLevel);
请参阅下面的代码,该代码是从电池服务的更新方法中的Android系统代码中删除的:
/* The ACTION_BATTERY_LOW broadcast is sent in these situations:
* - is just un-plugged (previously was plugged) and battery level is
* less than or equal to WARNING, or
* - is not plugged and battery level falls to WARNING boundary
* (becomes <= mLowBatteryWarningLevel).
*/
final boolean sendBatteryLow = !plugged
&& mBatteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN
&& mBatteryLevel <= mLowBatteryWarningLevel
&& (oldPlugged || mLastBatteryLevel > mLowBatteryWarningLevel);
sendIntent();
// Separate broadcast is sent for power connected / not connected
// since the standard intent will not wake any applications and some
// applications may want to have smart behavior based on this.
Intent statusIntent = new Intent();
statusIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
if (mPlugType != 0 && mLastPlugType == 0) {
statusIntent.setAction(Intent.ACTION_POWER_CONNECTED);
mContext.sendBroadcast(statusIntent);
}
else if (mPlugType == 0 && mLastPlugType != 0) {
statusIntent.setAction(Intent.ACTION_POWER_DISCONNECTED);
mContext.sendBroadcast(statusIntent);
}
if (sendBatteryLow) {
mSentLowBatteryBroadcast = true;
statusIntent.setAction(Intent.ACTION_BATTERY_LOW);
mContext.sendBroadcast(statusIntent);
答案 1 :(得分:6)
这个意图是从BatteryService发起的。你必须稍微分析一下代码,但我很确定它不会反复激发:
http://gitorious.org/android-eeepc/base/blobs/fda6fae156e31a287e3cfbf66e51ea1405cdf479/services/java/com/android/server/BatteryService.java
它触发的实际值是在android资源中设置的,因此它只能在系统构建期间进行配置。这就是我们的硬件,但对于Android运行的每个硬件平台,这可能会有所不同:
<!-- Display low battery warning when battery level dips to this value -->
<integer name="config_lowBatteryWarningLevel">15</integer>
<!-- Close low battery warning when battery level reaches this value -->
<integer name="config_lowBatteryCloseWarningLevel">20</integer>
除非您正在开发自定义硬件平台,否则我不会对这些值的设置做出任何假设。
答案 2 :(得分:0)
还有另一种方法可以从“com.android.internal.R.integer”字段中检测“config_lowBatteryWarningLevel”。
enter code here
try {
Class clazz = Class.forName("com.android.internal.R$integer");
Field field = clazz.getDeclaredField("config_lowBatteryWarningLevel");
field.setAccessible(true);
int LowBatteryLevel = _context.getResources().getInteger(field.getInt(null));
Log.d("LowBattery","warninglevel " + LowBatteryLevel);
} catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}