电池状态始终不充电

时间:2012-07-22 18:20:54

标签: java android status power-management

@Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
    BatteryManager.BATTERY_STATUS_UNKNOWN);

    if (status == BatteryManager.BATTERY_STATUS_CHARGING
        || status == BatteryManager.BATTERY_STATUS_FULL)
        Toast.makeText(context, "Charging!", Toast.LENGTH_SHORT).show();
    else
        Toast.makeText(context, "Not Charging!", Toast.LENGTH_SHORT).show();
}

清单:

<receiver android:name=".receiver.BatteryReceiver">
    <intent-filter>
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
        <action android:name="android.intent.action.BATTERY_CHANGED" />
    </intent-filter>
</receiver>

在此代码中,Toast始终显示“Not Charging!”。我在实际设备上对此进行了测试,当我将其插入AC或USB电源时,它仍显示“Not Charging!”烤面包。

2 个答案:

答案 0 :(得分:6)

您无法通过清单注册ACTION_BATTERY_CHANGED,因此您没有收到这些广播。您正试图从BatteryManager获取Intents个没有额外内容的额外内容(例如ACTION_POWER_CONNECTED)。因此,您将获得默认值BATTERY_STATUS_UNKNOWN

答案 1 :(得分:3)

尝试以下方法:

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

'status'现在是介于1和5之间的值:

1 = Unknown
2 = Charging
3 = Discharging
4 = Not Charging
5 = Full

您的代码:

if (status == BatteryManager.BATTERY_STATUS_CHARGING
    || status == BatteryManager.BATTERY_STATUS_FULL) ...

可写:

if (status == 2 || status == 5) ...

两者都是相同的,因为BatteryManager.BATTERY_STATUS_CHARGING是总是等于2的常量,而BatteryManager.BATTERY_STATUS_FULL是总是等于5的常量。