我正在尝试检测用户何时插入(或拔出)他们的设备进行充电。在我的接收器中,当我确定它是否插入时,我总是得到一个“错误”的状态读数。这是我的代码:
(在 list 中):
<receiver android:name=".PowerConnectionReceiver" >
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
这是 PowerConnectionReceiver 类:
public class PowerConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
Log.d("Battery", "Plugged In: " + String.valueOf(isCharging));
Log.d("Battery", "status: " + String.valueOf(status));
}
}
工作原理:插入电话时会正确调用 PowerConnectionReceiver。
但是,当我打印出状态时,它总是返回 -1(这是我输入的默认值)。 BatteryManager.EXTRA_STATUS 似乎没有正常进入。
作为引用,以下是这些日志打印出的内容:
"Plugged In: false"
"status: -1"
更多引用 - 这是我为此使用的开发者网站上的页面: http://developer.android.com/training/monitoring-device-state/battery-monitoring.html
最佳答案
知道了...这个答案来自本网站上另一篇关于电池的不同问题的帖子。
public class PowerConnectionReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if(action.equals(Intent.ACTION_POWER_CONNECTED))
{
// Do code here for when power connected
}
else if(action.equals(Intent.ACTION_POWER_DISCONNECTED))
{
// Do code here for when power disconnected
}
}
虽然这个答案并不完全优雅,但任何足够熟悉如何访问 intent.getAction() 附带的其他属性的人都应该能够对电池信息做更多的事情。否则,这就是我需要它做的一切!干杯。
关于java - 为什么我的充电状态接收器总是返回错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29765146/