为什么我的Receiver充电状态总是返回false?

时间:2015-04-21 07:03:36

标签: java android battery receiver

我试图检测用户何时插入(或拔下)设备进行充电。在我的接收器中,我确定它是否插入,我总是得到一个" false"阅读状态。这是我的代码:

(在清单中):

<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

2 个答案:

答案 0 :(得分:2)

知道了......这个答案来自本网站上关于电池的另一个问题的另一篇文章。

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()附带的其他属性的人都应该能够使用电池信息做更多的事情。否则,这就是我需要做的一切!欢呼声。

答案 1 :(得分:0)

我可能错了,但似乎状态代表一组标志。例如,电池可以充满电并仍然连接到充电器。所以你可以尝试的不是使用&#34; ==&#34;运算符,尝试应用位掩码。像这样:

boolean usbCharge = chargePlug & BatteryManager.BATTERY_PLUGGED_USB == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug & BatteryManager.BATTERY_PLUGGED_AC == BatteryManager.BATTERY_PLUGGED_AC;

来自BatteryManager来源:

/** Power source is an AC charger. */
public static final int BATTERY_PLUGGED_AC = 1;
/** Power source is a USB port. */
public static final int BATTERY_PLUGGED_USB = 2;
/** Power source is wireless. */
public static final int BATTERY_PLUGGED_WIRELESS = 4;

/** @hide */
public static final int BATTERY_PLUGGED_ANY =
        BATTERY_PLUGGED_AC | BATTERY_PLUGGED_USB | BATTERY_PLUGGED_WIRELESS;

因此电源可能是位的叠加

同样适用于状态变量:

boolean isCharging = 
        (status & BatteryManager.BATTERY_STATUS_CHARGING == BatteryManager.BATTERY_STATUS_CHARGING)
     || (status & BatteryManager.BATTERY_STATUS_FULL == BatteryManager.BATTERY_STATUS_FULL);