Android Open Source - android_device Battery Impl






From Project

Back to project page android_device.

License

The source code is released under:

[Apache License](http://www.apache.org/licenses/): Version 2.0, January 2004 =============== ## TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION ## ### 1. Definitions. ### "License" sha...

If you think the Android project android_device listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*
 * =================================================================================================
 *                Copyright (C) 2013 - 2014 Martin Albedinsky [Wolf-ITechnologies]
 * =================================================================================================
 *         Licensed under the Apache License, Version 2.0 or later (further "License" only).
 * -------------------------------------------------------------------------------------------------
 * You may use this file only in compliance with the License. More details and copy of this License
 * you may obtain at//w ww .  j  ava 2 s .c  om
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * You can redistribute, modify or publish any part of the code written within this file but as it
 * is described in the License, the software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES or CONDITIONS OF ANY KIND.
 *
 * See the License for the specific language governing permissions and limitations under the License.
 * =================================================================================================
 */
package com.wit.android.device;

import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.support.annotation.NonNull;
import android.util.Log;

import com.wit.android.device.receiver.BatteryHealthReceiver;
import com.wit.android.device.receiver.BatteryPluggedStateReceiver;
import com.wit.android.device.receiver.BatteryStatusReceiver;

import java.util.ArrayList;
import java.util.List;

/**
 * <h3>Class Overview</h3>
 * Implementation of {@link com.wit.android.device.Battery} wrapper for {@link com.wit.android.device.AndroidDevice AndroidDevice}.
 *
 * @author Martin Albedinsky
 */
final class BatteryImpl implements Battery {

  /**
   * Interface ===================================================================================
   */

  /**
   * Constants ===================================================================================
   */

  /**
   * Log TAG.
   */
  private static final String TAG = "BatteryImpl";

  /**
   * Flag indicating whether the debug output trough log-cat is enabled or not.
   */
  private static final boolean DEBUG_ENABLED = DeviceConfig.LIBRARY_DEBUG_LOG_ENABLED;

  /**
   * Flag indicating whether the output trough log-cat is enabled or not.
   */
  private static final boolean LOG_ENABLED = DeviceConfig.LIBRARY_LOG_ENABLED;

  /**
   * Static members ==============================================================================
   */

  /**
   * Members =====================================================================================
   */

  /**
   * Application context obtained from the context passed during initialization of this wrapper.
   */
  private final Context mContext;

  /**
   * Value of the battery strength to indicate low battery level.
   */
  private int mHealthLowLevel = HEALTH_LOW_LEVEL;

  /**
   * Value of the battery strength to indicate OK battery level.
   */
  private int mHealthOkLevel = HEALTH_OK_LEVEL;

  /**
   * Battery status receiver (broadcast receiver) to receive battery status changes.
   */
  private BatteryStatusReceiver mStatusReceiver;

  /**
   * Battery health receiver (broadcast receiver) to receive battery health changes.
   */
  private BatteryHealthReceiver mHealthReceiver;

  /**
   * Battery plugged state receiver (broadcast receiver) to receive battery plugged state changes.
   */
  private BatteryPluggedStateReceiver mPluggedStateReceiver;

  /**
   * Current battery data. This is only for battery status changes management.
   */
  private BatteryInfo mCurrentInfo = new BatteryInfo();

  /**
   * Previous battery data. This is only for battery status changes management.
   */
  private BatteryInfo mPrevInfo;

  /**
   * Array with status listeners.
   */
  private List<OnStatusListener> mStatusListeners;

  /**
   * Array with health listeners.
   */
  private List<OnHealthListener> mHealthListeners;

  /**
   * Array with charge listeners.
   */
  private List<OnPluggedStateListener> mPluggedStateListeners;

  /**
   * Flag indicating whether the receiver is registered or not.
   */
  private boolean mStatusReceiverRegistered, mHealthReceiverRegistered, mPluggedStateReceiverRegistered;

  /**
   * Flag indicating whether the persistent data about battery are initialized or not.
   */
  private boolean mPersistentDataInitialized;

  /**
   * Flag indicating whether the current battery data are initialized or not.
   */
  private boolean mDataInitialized;

  /**
   * Constructors ================================================================================
   */

  /**
   * Creates a new instance of BatteryImpl wrapper.
   *
   * @param context Application context or activity context.
   */
  BatteryImpl(Context context) {
    this.mContext = context.getApplicationContext();
  }

  /**
   * Methods =====================================================================================
   */

  /**
   * Public --------------------------------------------------------------------------------------
   */

  /**
   */
  @Override
  public void registerAllBatteryReceivers(@NonNull Context context) {
    registerBatteryReceiver(context, BatteryImpl.RECEIVER_BATTERY_STATUS);
    registerBatteryReceiver(context, BatteryImpl.RECEIVER_BATTERY_HEALTH);
    registerBatteryReceiver(context, BatteryImpl.RECEIVER_BATTERY_PLUGGED_STATE);
  }

  /**
   */
  @Override
  public void registerBatteryReceiver(@NonNull Context context, int receiverId) {
    final String receiverName = getReceiverName(receiverId);
    if (context == null) {
      Log.e(TAG, "Registering of the battery receiver(" + receiverName + ") failed. Given context is invalid.");
      return;
    }

    synchronized (this) {
      // Check already registered receiver.
      if (isBatteryReceiverRegistered(receiverId)) {
        if (LOG_ENABLED)
          Log.v(TAG, "Battery receiver(" + receiverName + ") already registered.");
      } else {
        final BatteryBroadcastReceiver receiver = getReceiver(receiverId);
        context.registerReceiver(receiver, receiver.newIntentFilter());
        switch (receiverId) {
          case RECEIVER_BATTERY_HEALTH:
            this.mHealthReceiverRegistered = true;
            break;
          case RECEIVER_BATTERY_PLUGGED_STATE:
            this.mPluggedStateReceiverRegistered = true;
            break;
          case RECEIVER_BATTERY_STATUS:
            this.mStatusReceiverRegistered = true;
            break;
        }
        if (LOG_ENABLED)
          Log.v(TAG, "Battery receiver(" + receiverName + ") successfully registered.");
      }
    }

  }

  /**
   */
  @Override
  public void unregisterAllBatteryReceivers(@NonNull Context context) {
    unregisterBatteryReceiver(context, BatteryImpl.RECEIVER_BATTERY_STATUS);
    unregisterBatteryReceiver(context, BatteryImpl.RECEIVER_BATTERY_HEALTH);
    unregisterBatteryReceiver(context, BatteryImpl.RECEIVER_BATTERY_PLUGGED_STATE);
  }

  /**
   */
  @Override
  public void unregisterBatteryReceiver(@NonNull Context context, int receiverId) {
    final String receiverName = getReceiverName(receiverId);
    if (context == null) {
      Log.e(TAG, "Un-Registering of the battery receiver(" + receiverName + ") failed. Given context is invalid.");
      return;
    }

    synchronized (this) {
      // Check if is receiver registered.
      if (!isBatteryReceiverRegistered(receiverId)) {
        if (LOG_ENABLED) {
          Log.v(TAG, "Can't un-register not registered battery receiver(" + receiverName + ").");
        }
      } else {
        final BatteryBroadcastReceiver receiver = getReceiver(receiverId);
        context.unregisterReceiver(receiver);
        dispatchBatteryReceiverUnregistered(receiverId);
        if (LOG_ENABLED) {
          Log.v(TAG, "Battery receiver(" + receiverName + ") successfully unregistered.");
        }
      }
    }
  }

  /**
   */
  @Override
  public final void dispatchBatteryReceiverUnregistered(int receiverId) {
    switch (receiverId) {
      case RECEIVER_BATTERY_STATUS:
        this.mStatusReceiverRegistered = false;
        break;
      case RECEIVER_BATTERY_HEALTH:
        this.mHealthReceiverRegistered = false;
        break;
      case RECEIVER_BATTERY_PLUGGED_STATE:
        this.mPluggedStateReceiverRegistered = false;
        break;
    }
    onBatteryReceiverUnregistered(receiverId);
  }

  /**
   */
  @Override
  public boolean isBatteryReceiverRegistered(int receiverId) {
    switch (receiverId) {
      case RECEIVER_BATTERY_STATUS:
        return mStatusReceiverRegistered;
      case RECEIVER_BATTERY_HEALTH:
        return mHealthReceiverRegistered;
      case RECEIVER_BATTERY_PLUGGED_STATE:
        return mPluggedStateReceiverRegistered;
    }
    return false;
  }

  /**
   */
  @Override
  public void registerOnBatteryListener(@NonNull BatteryListener listener) {
    this.handleBatteryListener(listener, true);
  }

  /**
   */
  @Override
  public void unregisterOnBatteryListener(@NonNull BatteryListener listener) {
    this.handleBatteryListener(listener, false);
  }

  /**
   */
  @Override
  public boolean isCharging() {
    this.checkDataInitialization("charging state");
    final BatteryStatus status = getStatus();
    return (status == BatteryStatus.CHARGING || status == BatteryStatus.FULL);
  }

  /**
   */
  @Override
  public boolean isPlugged() {
    this.checkDataInitialization("plugged state");
    final BatteryPluggedState state = getPluggedState();
    return (state != BatteryPluggedState.UNKNOWN && state != BatteryPluggedState.NOT_PLUGGED);
  }

  /**
   */
  @Override
  public boolean isLow() {
    return (getStrength() <= getHealthLowLevel());
  }

  /**
   */
  @Override
  public void processReceivedBroadcast(@NonNull Context context, @NonNull Intent intent, int receiverId) {
    // Obtain intent action.
    final String action = intent.getAction();
    if (action == null) {
      return;
    }

    // Resolve which receiver receives broadcast.
    switch (receiverId) {
      case RECEIVER_BATTERY_STATUS:
        if (DEBUG_ENABLED) {
          Log.d(TAG, "onBroadcastReceived() for BatteryStatusReceiver");
        }

        // Update data to actual ones.
        this.bindBatteryData(intent, receiverId);

        // Fire callback for listener.
        notifyBatteryStatusChange(context);
        break;
      case RECEIVER_BATTERY_HEALTH:
        if (DEBUG_ENABLED) {
          Log.d(TAG, "onBroadcastReceived() for BatteryHealthReceiver");
        }
        // This is fired whenever the battery level reach the LOW level or
        // OK level value of its strength.
        // Intent is not fired repeatedly, but only when the battery reach
        // low level from the OK level or on the contrary when the battery
        // reach OK level from the low level.
        // =================================================================
        // Fire callback for listeners.
        notifyBatteryHealthChange(context, action.equals(Intent.ACTION_BATTERY_LOW));
        break;
      case RECEIVER_BATTERY_PLUGGED_STATE:
        if (DEBUG_ENABLED) {
          Log.d(TAG, "onBroadcastReceived() for BatteryPluggedStateReceiver");
        }
        // This is fired whenever the power is connected/disconnected
        // to/from the battery. We want to just determine if this is connect
        // or disconnect.
        // =================================================================
        // Fire callback for listeners.
        notifyBatteryPluggedStateChange(context, action.equals(Intent.ACTION_POWER_CONNECTED));
        break;
    }
  }

  /**
   * Getters + Setters ---------------------------------------------------------------------------
   */

  /**
   * Returns an application context obtained from the context passed during initialization of this
   * wrapper.
   *
   * @return Application context.
   */
  public Context getApplicationContext() {
    return mContext;
  }

  /**
   */
  @Override
  public int getStrength() {
    this.checkDataInitialization("strength");
    return mCurrentInfo.strength();
  }

  /**
   */
  @NonNull
  @Override
  public BatteryStatus getStatus() {
    this.checkDataInitialization("status");
    return mCurrentInfo.status();
  }

  /**
   */
  @NonNull
  @Override
  public BatteryPluggedState getPluggedState() {
    this.checkDataInitialization("plugged state");
    return mCurrentInfo.pluggedState();
  }

  /**
   */
  @NonNull
  @Override
  public BatteryHealth getHealth() {
    this.checkDataInitialization("health");
    return mCurrentInfo.health();
  }

  /**
   */
  @NonNull
  @Override
  public BatteryTechnology getTechnology() {
    this.checkDataInitialization("technology");
    return mCurrentInfo.technology();
  }

  /**
   */
  @Override
  public float getTemperature() {
    this.checkDataInitialization("temperature");
    return mCurrentInfo.temperature();
  }

  /**
   */
  @Override
  public int getVoltage() {
    this.checkDataInitialization("voltage");
    return mCurrentInfo.voltage();
  }

  /**
   */
  @Override
  public void setHealthLowLevel(int level) {
    if (level >= 0 && level <= 100) {
      this.mHealthLowLevel = level;
    }
  }

  /**
   */
  @Override
  public int getHealthLowLevel() {
    return mHealthLowLevel;
  }

  /**
   */
  @Override
  public void setHealthOkLevel(int level) {
    if (level >= 0 && level <= 100) {
      this.mHealthOkLevel = level;
    }
  }

  /**
   */
  @Override
  public int getHealthOkLevel() {
    return mHealthOkLevel;
  }

  /**
   * Protected -----------------------------------------------------------------------------------
   */

  /**
   * Private -------------------------------------------------------------------------------------
   */

  /**
   * Invoked when a battery receiver with the specified <var>receiverId</var> was currently un-registered.
   *
   * @param receiverId The id of currently un-registered receiver.
   */
  private void onBatteryReceiverUnregistered(int receiverId) {
    switch (receiverId) {
      case RECEIVER_BATTERY_STATUS:
        // Dispatch to reset status data.
        mCurrentInfo.resetStatusData();
        mPrevInfo.resetStatusData();

        // Reset all status receiver flags.
        this.mPersistentDataInitialized = this.mDataInitialized = false;

        // Dispatch to reset both plugged and health state.
        mCurrentInfo.resetHealthState();
        mCurrentInfo.resetPluggedState();
        mPrevInfo.resetHealthState();
        mPrevInfo.resetPluggedState();
        break;
      case RECEIVER_BATTERY_HEALTH:
        mCurrentInfo.resetHealthState();
        mPrevInfo.resetHealthState();
        break;
      case RECEIVER_BATTERY_PLUGGED_STATE:
        mCurrentInfo.resetPluggedState();
        mPrevInfo.resetPluggedState();
        break;
    }
  }

  /**
   * Checks whether the current battery data are initialized or not.
   *
   * @param batteryInfo Cause, why the initialization state of the battery data is being checked.
   * @return {@code True} if data are initialized, {@code false} otherwise.
   */
  private boolean checkDataInitialization(String batteryInfo) {
    if (!mDataInitialized && !mStatusReceiverRegistered) {
      if (LOG_ENABLED) {
        Log.v(TAG, "Can not to determine " + batteryInfo + " of the battery. The BatteryStatusReceiver isn't registered?");
      }
    }
    return mDataInitialized;
  }

  /**
   * Handles registering/un-registering of the given listener.
   *
   * @param listener Listener to register/un-register.
   * @param register {@code True} to register, {@code false} to un-register listener.
   */
  private void handleBatteryListener(BatteryListener listener, boolean register) {
    if (listener instanceof SimpleListener) {
      final SimpleListener simpleListener = (SimpleListener) listener;
      if (register) {
        this.addStatusListener(simpleListener);
        this.addPluggedListener(simpleListener);
        this.addHealthListener(simpleListener);
      } else {
        this.removeHealthListener(simpleListener);
        this.removeStatusListener(simpleListener);
        this.removePluggedListener(simpleListener);
      }
    } else if (listener instanceof OnStatusListener) {
      if (register) {
        addStatusListener((OnStatusListener) listener);
      } else {
        this.removeStatusListener((OnStatusListener) listener);
      }
    } else if (listener instanceof OnPluggedStateListener) {
      if (register) {
        addPluggedListener((OnPluggedStateListener) listener);
      } else {
        this.removePluggedListener((OnPluggedStateListener) listener);
      }
    } else if (listener instanceof OnHealthListener) {
      if (register) {
        addHealthListener((OnHealthListener) listener);
      } else {
        this.removeHealthListener((OnHealthListener) listener);
      }
    } else if (LOG_ENABLED) {
      Log.v(TAG, "Unknown battery listener type(" + listener.getClass().getSimpleName()
          + ") when registering/un-registering BatteryListener.");
    }
  }

  /**
   * Notifies all current {@link com.wit.android.device.Battery.OnStatusListener} listeners, that some of the battery status
   * values was changed.
   *
   * @param context Current application context.
   */
  private void notifyBatteryStatusChange(Context context) {
    for (OnStatusListener listener : mStatusListeners) {
      if (listener != null) {
        listener.onStatusChange(this, context);
      }
    }

    // Check for changed health or plugged status.
    if (mPrevInfo != null) {
      if (!mHealthReceiverRegistered) {
        switch (mPrevInfo.getHealthStatus(mCurrentInfo.strength())) {
          case BatteryInfo.HEALTH_LEVEL_STATUS_UNCHANGED:
            break;
          case BatteryInfo.HEALTH_LEVEL_STATUS_LOW:
            notifyBatteryHealthChange(context, true);
            break;
          case BatteryInfo.HEALTH_LEVEL_STATUS_OK:
            notifyBatteryHealthChange(context, false);
            break;
        }
      }
      if (!mPluggedStateReceiverRegistered) {
        if (mPrevInfo.hasPluggedStateChanged(mCurrentInfo.pluggedState)) {
          notifyBatteryPluggedStateChange(context, isPlugged());
        }
      }
    }
  }

  /**
   * Notifies all current {@link com.wit.android.device.Battery.OnHealthListener} listeners, that the health state of battery
   * was changed.
   *
   * @param context Current application context.
   * @param low     {@code True} if the current health of battery is low, {@code false} otherwise.
   */
  private void notifyBatteryHealthChange(Context context, boolean low) {
    for (OnHealthListener listener : mHealthListeners) {
      if (listener != null) {
        listener.onHealthChange(this, low, context);
      }
    }
    // Dispatch to reset status data.
    mCurrentInfo.resetStatusData();
    mPrevInfo.resetStatusData();
  }

  /**
   * Notifies all current {@link com.wit.android.device.Battery.OnPluggedStateListener}
   * listeners, that the plugged state of battery was changed.
   *
   * @param context Current application context.
   * @param plugged {@code True} if battery is currently plugged to some source,
   *                {@code false} otherwise.
   */
  private void notifyBatteryPluggedStateChange(Context context, boolean plugged) {
    for (OnPluggedStateListener listener : mPluggedStateListeners) {
      if (listener != null) {
        listener.onPluggedStateChange(this, plugged, context);
      }
    }
  }

  /**
   * Returns the battery receiver associated with the requested <var>receiverId</var>.
   *
   * @param receiverId Id of the battery receiver.
   * @return One of battery receivers.
   */
  private BatteryBroadcastReceiver getReceiver(int receiverId) {
    BatteryBroadcastReceiver receiver = null;
    synchronized (this) {
      switch (receiverId) {
        case RECEIVER_BATTERY_STATUS:
          receiver = (mStatusReceiver == null) ? mStatusReceiver = new BatteryStatusReceiver() : mStatusReceiver;
          break;
        case RECEIVER_BATTERY_HEALTH:
          receiver = (mHealthReceiver == null) ? mHealthReceiver = new BatteryHealthReceiver() : mHealthReceiver;
          break;
        case RECEIVER_BATTERY_PLUGGED_STATE:
          receiver = (mPluggedStateReceiver == null) ? mPluggedStateReceiver = new BatteryPluggedStateReceiver() : mPluggedStateReceiver;
          break;
      }
    }
    return receiver;
  }

  /**
   * Returns a name of the battery receiver associated with the requested <var>receiverId</var>.
   *
   * @param receiverId Id of the battery receiver which name to obtain.
   * @return Battery receiver's name.
   */
  private String getReceiverName(int receiverId) {
    String name = "";
    switch (receiverId) {
      case RECEIVER_BATTERY_STATUS:
        name = "BATTERY_STATUS_RECEIVER";
        break;
      case RECEIVER_BATTERY_HEALTH:
        name = "BATTERY_HEALTH_RECEIVER";
        break;
      case RECEIVER_BATTERY_PLUGGED_STATE:
        name = "BATTERY_PLUGGED_STATE_RECEIVER";
        break;
    }
    return name;
  }

  /**
   * Binds the current battery data with that ones (actual) from the given intent.
   *
   * @param intent     Intent with the actual battery data.
   * @param receiverId Id of the battery receiver which receives the given intent.
   */
  private void bindBatteryData(Intent intent, int receiverId) {
    // Save previous battery info.
    this.mPrevInfo = new BatteryInfo(mCurrentInfo);

    // Initialize persistent data only if this is first binding.
    if (!mPersistentDataInitialized) {
      final String technology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY);
      mCurrentInfo.technology = BatteryTechnology.resolve(technology);
      mCurrentInfo.voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, mCurrentInfo.voltage);
      this.mPersistentDataInitialized = true;
      if (DEBUG_ENABLED) {
        Log.d(TAG, "bindBatteryData() technology = " + technology);
      }
    }

    /**
     * Update data to actual ones.
     */
    // Status.
    mCurrentInfo.status = BatteryStatus.resolve(intent.getIntExtra(
        BatteryManager.EXTRA_STATUS,
        mCurrentInfo.status.systemConstant));

    // Temperature.
    mCurrentInfo.temperature = intent.getIntExtra(
        BatteryManager.EXTRA_TEMPERATURE,
        mCurrentInfo.temperature);

    // Strength.
    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);
    final float strength = level / (float) scale;
    if (strength >= 0) {
      mCurrentInfo.strength = strength;
    }

    // Health.
    mCurrentInfo.health = BatteryHealth.resolve(intent.getIntExtra(
        BatteryManager.EXTRA_HEALTH,
        mCurrentInfo.health.systemConstant));

    // Plugged state.
    mCurrentInfo.pluggedState = BatteryPluggedState.resolve(intent.getIntExtra(
        BatteryManager.EXTRA_PLUGGED,
        mCurrentInfo.pluggedState.systemConstant));

    // Save initialization state.
    this.mDataInitialized = true;
    mCurrentInfo.logCurrentData();
  }

  /**
   * Adds the given listener into the current set of status listeners.
   *
   * @param listener Listener to add.
   */
  private void addStatusListener(OnStatusListener listener) {
    if (mStatusListeners == null) {
      this.mStatusListeners = new ArrayList<>();
      mStatusListeners.add(listener);
      if (mDataInitialized) {
        // Fire initial callback.
        notifyBatteryStatusChange(getApplicationContext());
      }
      return;
    }
    if (!mStatusListeners.contains(listener)) {
      mStatusListeners.add(listener);
      if (mDataInitialized) {
        // Fire initial callback.
        notifyBatteryStatusChange(getApplicationContext());
      }
    }
  }

  /**
   * Removes the given listener from the current set of status listeners.
   *
   * @param listener Listener to remove.
   */
  private void removeStatusListener(OnStatusListener listener) {
    if (mStatusListeners != null) {
      mStatusListeners.remove(listener);
    }
  }

  /**
   * Adds the given listener into the current set of plugged state listeners.
   *
   * @param listener Listener to add.
   */
  private void addPluggedListener(OnPluggedStateListener listener) {
    if (mPluggedStateListeners == null) {
      this.mPluggedStateListeners = new ArrayList<>();
      mPluggedStateListeners.add(listener);
      return;
    }
    if (!mPluggedStateListeners.contains(listener)) {
      mPluggedStateListeners.add(listener);
    }
  }

  /**
   * Removes the given listener from the current ste of plugged state listeners.
   *
   * @param listener Listener to remove.
   */
  private void removePluggedListener(OnPluggedStateListener listener) {
    if (mPluggedStateListeners != null) {
      mPluggedStateListeners.remove(listener);
    }
  }

  /**
   * Adds the given listener into the current set of health listeners.
   *
   * @param listener Listener to add.
   */
  private void addHealthListener(OnHealthListener listener) {
    if (mHealthListeners == null) {
      this.mHealthListeners = new ArrayList<>();
      mHealthListeners.add(listener);
      return;
    }
    if (!mHealthListeners.contains(listener)) {
      mHealthListeners.add(listener);
    }
  }

  /**
   * Removes the given listener from the current set of health listeners.
   *
   * @param listener Listener to remove.
   */
  private void removeHealthListener(OnHealthListener listener) {
    if (mHealthListeners != null) {
      mHealthListeners.remove(listener);
    }
  }

  /**
   * Abstract methods ----------------------------------------------------------------------------
   */

  /**
   * Inner classes ===============================================================================
   */

  /**
   * Battery info data holder.
   */
  private final class BatteryInfo {

    /**
     * Constants ===============================================================================
     */

    /**
     * Flag indicating, that battery health level status in unchanged.
     */
    private static final int HEALTH_LEVEL_STATUS_UNCHANGED = 0x00;

    /**
     * Flag indicating, that battery health reaches OK level.
     */
    private static final int HEALTH_LEVEL_STATUS_OK = 0x01;

    /**
     * Flag indicating, that battery health drops below OK level to LOW level.
     */
    private static final int HEALTH_LEVEL_STATUS_LOW = 0x02;

    /**
     * Members =================================================================================
     */

    /**
     * Status of the current Android device's battery like {@link BatteryStatus#CHARGING}.
     */
    BatteryStatus status = BatteryStatus.UNKNOWN;

    /**
     * Status of the current Android device's battery plugged state like {@link BatteryPluggedState#USB}.
     */
    BatteryPluggedState pluggedState = BatteryPluggedState.UNKNOWN;

    /**
     * Technology of the current Android device's battery.
     */
    BatteryTechnology technology = BatteryTechnology.UNKNOWN;

    /**
     * Status of the current Android device's battery health state like {@link BatteryHealth#OVERHEAT}.
     */
    BatteryHealth health = BatteryHealth.UNKNOWN;

    /**
     * Strength of the current Android device's battery life as percentage value.
     */
    float strength = -0.01f;

    /**
     * Temperature of the current Android device's battery.
     */
    int temperature = -1;

    /**
     * Voltage of the current Android device's battery.
     */
    int voltage = -1;

    /**
     * Constructors ============================================================================
     */

    /**
     * Creates a new empty instance of BatteryInfo unknown data for all battery parameters.
     */
    BatteryInfo() {
    }

    /**
     * Creates a new instance of BatteryInfo with the data copied from the given <var>other</var>
     * battery info holder.
     *
     * @param other Battery info holder of which data to copy.
     */
    BatteryInfo(BatteryInfo other) {
      this.health = BatteryHealth.resolve(other.health.systemConstant);
      this.status = BatteryStatus.resolve(other.status.systemConstant);
      this.pluggedState = BatteryPluggedState.resolve(other.pluggedState.systemConstant);
      this.technology = BatteryTechnology.resolve(other.technology.tagName);
      this.strength = other.strength;
      this.temperature = other.temperature;
      this.voltage = other.voltage;
    }

    /**
     * Methods =================================================================================
     */

    /**
     * @return Status of the current Android device's battery like {@link BatteryStatus#CHARGING}.
     */
    public BatteryStatus status() {
      return status;
    }

    /**
     * @return Status of the current Android device's battery plugged state like {@link BatteryPluggedState#USB}.
     */
    public BatteryPluggedState pluggedState() {
      return pluggedState;
    }

    /**
     * @return Technology of the current Android device's battery.
     */
    public BatteryTechnology technology() {
      return technology;
    }

    /**
     * @return Status of the current Android device's battery health state like {@link BatteryHealth#OVERHEAT}.
     */
    public BatteryHealth health() {
      return health;
    }

    /**
     * @return Strength of the current Android device's battery life in the range {@code &lt;0, 100&gt;}.
     */
    public int strength() {
      return (int) (strength * 100);
    }

    /**
     * @return Temperature of the current Android device's battery in degree Contigrade.
     */
    public float temperature() {
      return temperature / 10.0f;
    }

    /**
     * @return Voltage of the current Android device's battery in milli-volts.
     */
    public int voltage() {
      return voltage;
    }

    /**
     * Resets the current value of health state of this info to {@link BatteryHealth#UNKNOWN}.
     */
    private void resetHealthState() {
      if (!mStatusReceiverRegistered) {
        // We don't know anymore the actual health state of the battery.
        this.health = BatteryHealth.UNKNOWN;
      }
    }

    /**
     * Resets the current value of plugged state of this info to {@link BatteryPluggedState#UNKNOWN}.
     */
    private void resetPluggedState() {
      // We don't know anymore the actual plugged state of the battery.
      if (!mStatusReceiverRegistered || !mPluggedStateReceiverRegistered) {
        this.pluggedState = BatteryPluggedState.UNKNOWN;
      }
    }

    /**
     * Resets the current value of status to {@link BatteryStatus#UNKNOWN} and value of strength
     * to {@code -1} of this info.
     */
    private void resetStatusData() {
      if (!mStatusReceiverRegistered) {
        // Reset all dynamically changing states.
        this.status = BatteryStatus.UNKNOWN;
        this.strength = this.temperature = -1;
      }
    }

    /**
     * Checks whether the current plugged state of this info is different from
     * {@link com.wit.android.device.Battery.BatteryPluggedState#UNKNOWN} and the given
     * <var>currentStatus</var>.
     *
     * @param currentStatus Current status to compare with the current plugged state of this info.
     * @return {@code True} if changed, {@code false} otherwise.
     */
    private boolean hasPluggedStateChanged(BatteryPluggedState currentStatus) {
      return pluggedState != BatteryPluggedState.UNKNOWN && pluggedState != currentStatus;
    }

    /**
     * @param currentHealthStrength The value of the current Android device's battery strength.
     * @return On of the {@link #HEALTH_LEVEL_STATUS_UNCHANGED}, {@link #HEALTH_LEVEL_STATUS_LOW},
     * {@link #HEALTH_LEVEL_STATUS_OK}.
     */
    public int getHealthStatus(int currentHealthStrength) {
      int status = HEALTH_LEVEL_STATUS_UNCHANGED;
      int prevHealthStrength = strength();
      if (prevHealthStrength != currentHealthStrength) {
        /**
         * Check if the battery strength gets below/above the
         * LOW/OK level like so:
         * --------------------------------------------------
         * -- battery is getting OK
         * OK level ======================
         * -- neutral area
         * LOW level =====================
         * -- battery is getting LOW
         * --------------------------------------------------
         */
        if (prevHealthStrength == (mHealthLowLevel + 1) && currentHealthStrength <= mHealthLowLevel) {
          status = HEALTH_LEVEL_STATUS_LOW;
        } else if (prevHealthStrength == mHealthOkLevel && currentHealthStrength > mHealthOkLevel) {
          status = HEALTH_LEVEL_STATUS_OK;
        }
      }
      return status;
    }

    /**
     * Logs the current data of this info to log-cat console.
     */
    private void logCurrentData() {
      if (DEBUG_ENABLED) {
        Log.d(TAG,
            "[" +
                "status(" + status.name() + "):" +
                "health(" + health.name() + "):" +
                "strength(" + getStrength() + "):" +
                "voltage(" + getVoltage() + "):" +
                "technology(" + technology.name() + "):" +
                "pluggedState(" + pluggedState.name() + "):" +
                "temperature(" + getTemperature() + ")" +
                "]"
        );
      }
    }
  }
}




Java Source Code List

com.wit.android.device.AndroidDevice.java
com.wit.android.device.BatteryImpl.java
com.wit.android.device.Battery.java
com.wit.android.device.ConnectionImpl.java
com.wit.android.device.Connection.java
com.wit.android.device.DeviceConfig.java
com.wit.android.device.ScreenImpl.java
com.wit.android.device.Screen.java
com.wit.android.device.StorageAction.java
com.wit.android.device.StorageImpl.java
com.wit.android.device.Storage.java
com.wit.android.device.examples.HomeActivity.java
com.wit.android.device.examples.adapter.BatteryInfoAdapter.java
com.wit.android.device.examples.adapter.ConnectionInfoAdapter.java
com.wit.android.device.examples.adapter.FilesAdapter.java
com.wit.android.device.examples.adapter.OrientationsAdapter.java
com.wit.android.device.examples.adapter.SimpleInfoAdapter.java
com.wit.android.device.examples.adapter.StorageAdapter.java
com.wit.android.device.examples.dialog.NewFileDialog.java
com.wit.android.device.examples.fragment.BaseDeviceFragment.java
com.wit.android.device.examples.fragment.BatteryInfoFragment.java
com.wit.android.device.examples.fragment.ConnectionInfoFragment.java
com.wit.android.device.examples.fragment.DeviceInfoFragment.java
com.wit.android.device.examples.fragment.FragmentsFactory.java
com.wit.android.device.examples.fragment.ScreenInfoFragment.java
com.wit.android.device.examples.fragment.ScreenInterfaceFragment.java
com.wit.android.device.examples.fragment.StorageFilesFragment.java
com.wit.android.device.examples.fragment.StorageInfoFragment.java
com.wit.android.device.examples.fragment.StorageInterfaceFragment.java
com.wit.android.device.examples.model.BatteryInfo.java
com.wit.android.device.examples.model.ConnectionInfo.java
com.wit.android.device.examples.model.SimpleInfo.java
com.wit.android.device.examples.model.StorageItem.java
com.wit.android.device.examples.module.StorageAssistant.java
com.wit.android.device.receiver.BatteryHealthReceiver.java
com.wit.android.device.receiver.BatteryPluggedStateReceiver.java
com.wit.android.device.receiver.BatteryStatusReceiver.java
com.wit.android.device.receiver.BroadcastProcessor.java
com.wit.android.device.receiver.ConnectionStateReceiver.java
com.wit.android.device.util.ConnectionUtils.java
com.wit.android.device.util.ScreenUtils.java
com.wit.android.device.util.StorageEditor.java
com.wit.android.device.util.StorageUtils.java