How can I get battery status info outside of both an activity and service?

StackOverflow https://stackoverflow.com/questions/19387112

  •  30-06-2022
  •  | 
  •  

سؤال

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