I have a class that extends Thread and it's instantiated in my Application class. It's purpose is to monitor various things about the operating system and then build a JSON object of monitored values and send them to a server every 20 seconds or so... one of the bits of data I'm supposed to collect is battery level information. I've only seen examples on how to do this from within an activity or service. Is there any way I can get this information from outside of an activity and service?

Thanks

有帮助吗?

解决方案

That sounds like a huge battery drain.

The Battery Manager will let you query for charging status, but you still need a context. Since you're instantiating this in the Application class, that works out for you.

Edit: just noticed that you'd already read the guide. Look at this section, and remember that the application itself is a valid context:

    final IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = this.registerReceiver(null, ifilter);
    int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top