Thanks Mark, that was the hint I needed.
What I really wanted to know was whether or not the battery was
currently in use, and for anybody else following this thread, here's
the method I came up with:
"
/**
* Is the battery currently discharging?
*
* @return True if our battery is discharging. False otherwise.
*/
private boolean isDischarging() {
// Contact the battery manager
Intent batteryIntent =
registerReceiver(null, new IntentFilter
(Intent.ACTION_BATTERY_CHANGED));
if (batteryIntent == null) {
Log.w(DrainOMeter.LOGGING_TAG,
"Failed to talk to the battery manager, assuming
we're on battery power");
return true;
}
// Ask about battery charging status
int batteryStatus = BatteryManager.BATTERY_STATUS_UNKNOWN;
if (batteryIntent != null) {
batteryStatus =
batteryIntent.getIntExtra("status",
BatteryManager.BATTERY_STATUS_UNKNOWN);
}
if (batteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) {
Log.w(DrainOMeter.LOGGING_TAG,
"Failed to get battery charging status, assuming
we're on battery power");
return true;
}
return batteryStatus ==
BatteryManager.BATTERY_STATUS_DISCHARGING;
}
"
Cheers //Johan
On 18 Sep, 11:54, Mark Murphy <[email protected]> wrote:
> Walles wrote:
> > I want to know if my device is currently charging.
>
> > How do I find that out? I've been looking a bit at the Intents API,
> > but AFAIU I can just subscribe to events from there, and a
> > subscription is not what I'm after. And even if I *did* want updates,
> > I'd still need to know the initial state.
>
> > I just want to ask a one-shot "are we charging" question. How can I
> > do that?
>
> Register for the broadcast Intent with a null receiver. If you get a
> non-null return value, then that return value is an Intent from the last
> "sticky broadcast" matching your supplied IntentFilter. I believe the
> battery updates are such a sticky broadcast. By passing null for the
> receiver, you do not actually register a receiver and so do not need to
> unregister anything later.
>
> For more instructions on this, look up registerReceiver() in the Context
> class (which is a base class for Activity, Service, etc.).
>
> --
> Mark Murphy (a Commons
> Guy)http://commonsware.com|http://twitter.com/commonsguy
>
> _The Busy Coder's Guide to *Advanced* Android Development_
> Version 1.1 Available!
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en
-~----------~----~----~----~------~----~------~--~---