【发布时间】:2012-07-21 02:47:36
【问题描述】:
@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 始终显示“未充电!”。我在实际设备上进行了测试,当我将其插入 AC 或 USB 电源时,它仍然显示“未充电!”吐司。
【问题讨论】:
-
intent 有问题。getIntExtra,检查从哪里调用此方法并确保使用正确的参数设置 Intent
-
你的状态是什么?
-
@John 我在清单中使用它。
-
@zmbq 我拔掉插头时得到 1,插入时得到 1。
标签: java android status power-management