As mentioned in the Broadcast Receiver post, updates will only be applied when the app is visible (between onResume and onPause). Therefore system changes which occur outside this window could leave the app with outdated information on resume. Therefore we should also check at onResume what the current system status is.
Depending on the version of Android the device is running you may be able to acquire a status directly from e.g. BatteryManager:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // If using a modern enough version of Android... BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE); // ...ask the appropriate service for a status check doSomething(batteryManager.isCharging()); // Returns a boolean you can feed back into your own methods } else // Otherwise use sticky intents (see below)Certain system broadcast intents do not disappear the moment they have fired and are processed. Instead they remain available to the system until superceded by a more up-to-date intent. These are known as sticky intents, and are the way of determining system status in older Android versions:
{ IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); // Create a new IntentFilter for the appropriate sticky Intent Intent chargingStatus = registerReceiver(null, intentFilter); // The same code you would use to register a Broadcast Receiver, but leave the first parameter null int batteryChargingStatus = chargingStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); // Get the info you want from the sticky Intent, with a default value boolean isCharging = batteryChargingStatus == BatteryManager.BATTERY_STATUS_CHARGING || batteryChargingStatus == BatteryManager.BATTERY_STATUS_FULL; // This will return a boolean of true if the phone is charging or fully charged doSomething(isCharging); // Feed the boolean into your own methods }ud851-Exercises-student\Lesson10-Hydration-Reminder\T10.06
