android.os.BatteryManager Java Examples

The following examples show how to use android.os.BatteryManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Battery.java    From batteryhub with Apache License 2.0 7 votes vote down vote up
/**
 * Get the battery capacity at the moment (in %, from 0-100)
 *
 * @param context Application context
 * @return Battery capacity (in %, from 0-100)
 */
public static int getBatteryCapacity(final Context context) {
    int value = 0;

    BatteryManager manager = (BatteryManager)
            context.getSystemService(Context.BATTERY_SERVICE);
    if (manager != null) {
        value = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
    }

    if (value != 0 && value != Integer.MIN_VALUE) {
        return value;
    }

    return 0;
}
 
Example #2
Source File: Battery.java    From batteryhub with Apache License 2.0 7 votes vote down vote up
/**
 * Calculate Average Power
 * Average Power = (Average Voltage * Average Current) / 1e9
 *
 * @param context Context of application
 * @return Average power in integer
 */
public static int getBatteryAveragePower(final Context context) {
    int voltage;
    int current = 0;

    Intent receiver =
            context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    if (receiver == null) return -1;

    voltage = receiver.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);

    BatteryManager manager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
    if (manager != null) {
        current = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE);
    }

    return (voltage * current) / 1000000000;
}
 
Example #3
Source File: DeviceSucker.java    From CameraV with GNU General Public License v3.0 7 votes vote down vote up
private void getPlugState(Intent intent) {
    String parse = null;
    int plugged_state = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);

    Logger.d(LOG, String.format("GETTING PLUG STATE: %d", plugged_state));

    switch(plugged_state) {
        case BatteryManager.BATTERY_PLUGGED_AC:
            parse = "battery plugged AC";
            break;
        case BatteryManager.BATTERY_PLUGGED_USB:
            parse = "battery plugged USB";
            break;
    }

    if(parse != null) {
        ILogPack logPack = new ILogPack();

        logPack.put(Keys.PLUG_EVENT_TYPE, parse);
        logPack.put(Keys.PLUG_EVENT_CODE, plugged_state);

        sendToBuffer(logPack);
    }
}
 
Example #4
Source File: Util.java    From android-notification-log with MIT License 6 votes vote down vote up
public static int getBatteryLevel(Context context) {
	if(Build.VERSION.SDK_INT >= 21) {
		BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
		if (bm != null) {
			try {
				return bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
			} catch (Exception e) {
				if(Const.DEBUG) e.printStackTrace();
			}
		}
	}
	return -1;
}
 
Example #5
Source File: DataEstimator.java    From batteryhub with Apache License 2.0 6 votes vote down vote up
public String getHealthStatus(final Context context) {
    String status = "";
    switch (mHealth) {
        case BatteryManager.BATTERY_HEALTH_UNKNOWN:
            status = context.getString(R.string.battery_health_unknown);
            break;
        case BatteryManager.BATTERY_HEALTH_GOOD:
            status = context.getString(R.string.battery_health_good);
            break;
        case BatteryManager.BATTERY_HEALTH_OVERHEAT:
            status = context.getString(R.string.battery_health_overheat);
            break;
        case BatteryManager.BATTERY_HEALTH_DEAD:
            status = context.getString(R.string.battery_health_dead);
            break;
        case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
            status = context.getString(R.string.battery_health_over_voltage);
            break;
        case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
            status = context.getString(R.string.battery_health_failure);
            break;
    }

    return status;
}
 
Example #6
Source File: MyReadBookActivity.java    From a with GNU General Public License v3.0 6 votes vote down vote up
@SuppressLint("DefaultLocale")
@Override
public void onReceive(Context context, Intent intent) {
    if (readBookControl.getHideStatusBar()) {
        if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) {
            if (mPageLoader != null) {
                mPageLoader.updateTime();
            }
        } else if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            if (mPageLoader != null) {
                mPageLoader.updateBattery(level);
            }
        }
    }
}
 
Example #7
Source File: LocationUpdateReceiver.java    From home-assistant-Android with GNU General Public License v3.0 6 votes vote down vote up
private void logLocation(@NonNull Location location, @NonNull Context context) {
    Log.d(TAG, "Sending location");
    String deviceName = Utils.getPrefs(context).getString(Common.PREF_LOCATION_DEVICE_NAME, null);
    if (TextUtils.isEmpty(deviceName)) {
        return;
    }

    Intent batteryStatus = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int percentage = 0;
    if (batteryStatus != null) {
        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, 1);
        percentage = Math.round(level / (float) scale * 100);
    }
    Intent serviceIntent = new Intent(context, HassService.class);
    serviceIntent.putExtra(EXTRA_ACTION_COMMAND, new DeviceTrackerRequest(deviceName, location.getLatitude(), location.getLongitude(), Math.round(location.getAccuracy()), percentage).toString());
    context.startService(serviceIntent);
}
 
Example #8
Source File: BatteryBroadcastReceiver.java    From DanDanPlayForAndroid with MIT License 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (intent == null || intent.getAction() == null)
        return;
    // 接收电量变化信息
    if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
        int level = intent.getIntExtra("level", 0);
        int scale = intent.getIntExtra("scale", 100);
        int status = intent.getIntExtra("status", BatteryManager.BATTERY_HEALTH_UNKNOWN);

        // 电量百分比
        int curPower = level * 100 / scale;

        if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
            listener.onBatteryChanged(BATTERY_STATUS_SPA, curPower);
        } else if (curPower < BATTERY_LOW_LEVEL) {
            listener.onBatteryChanged(BATTERY_STATUS_LOW, curPower);
        } else {
            listener.onBatteryChanged(BATTERY_STATUS_NOR, curPower);
        }
    }
}
 
Example #9
Source File: Battery.java    From batteryhub with Apache License 2.0 6 votes vote down vote up
/**
     * Get the battery full capacity (charge counter) in mAh.
     * Since Power (W) = (Current (A) * Voltage (V)) <=> Power (Wh) = (Current (Ah) * Voltage (Vh)).
     * Therefore, Current (mA) = Power (mW) / Voltage (mV)
     *
     * @param context Application context
     * @return Battery full capacity (in mAh)
     */
    public static int getBatteryChargeCounter(final Context context) {
        int value = 0;

        BatteryManager manager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
        if (manager != null) {
            value = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
        }

        return value;

//        if (value <= 0) {
//            value = getBatteryPropertyLegacy(Config.BATTERY_CHARGE_FULL);
//        }
//
//        if (value != 0 && value != Integer.MIN_VALUE) {
//            return value;
//        } else {
//            // in uAh
//            int chargeFullDesign =
//                    getBatteryPropertyLegacy(Config.BATTERY_ENERGY_FULL_DESIGN) / 1000000;
//            int chargeFull = chargeFullDesign != 0 ?
//                    chargeFullDesign :
//                    getBatteryPropertyLegacy(Config.BATTERY_ENERGY_FULL) / 1000000;
//
//            // in mAh
//            return (chargeFull != 0) ? chargeFull : -1;
//        }
    }
 
Example #10
Source File: SmsSenderService.java    From Locate-driver with GNU General Public License v3.0 6 votes vote down vote up
private long getBatteryPercentageIfApi21() {
    if(Build.VERSION.SDK_INT >= 21) {
        BatteryManager bm = (BatteryManager) getSystemService(BATTERY_SERVICE);
        return bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
    } else {
        return -1;
    }
}
 
Example #11
Source File: BatteryService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void shutdownIfNoPowerLocked() {
    // shut down gracefully if our battery is critically low and we are not powered.
    // wait until the system has booted before attempting to display the shutdown dialog.
    if (mHealthInfo.batteryLevel == 0 && !isPoweredLocked(BatteryManager.BATTERY_PLUGGED_ANY)) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (mActivityManagerInternal.isSystemReady()) {
                    Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
                    intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
                    intent.putExtra(Intent.EXTRA_REASON,
                            PowerManager.SHUTDOWN_LOW_BATTERY);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivityAsUser(intent, UserHandle.CURRENT);
                }
            }
        });
    }
}
 
Example #12
Source File: BatterySampleFragment.java    From genymotion-binocle with Apache License 2.0 6 votes vote down vote up
private void handleBatteryStatus(Intent batteryStatus) {

        // Are we charging / charged yet?
        int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = ( (status == BatteryManager.BATTERY_STATUS_CHARGING)
                || (status == BatteryManager.BATTERY_STATUS_FULL) );

        // How much power?
        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        float batteryPct = level / (float) scale;

        if (!isCharging && batteryPct < 0.10f) {
            Log.d(BatterySampleFragment.TAG, "Show battery warning");
            tvBatteryWarning.setVisibility(View.VISIBLE);
        } else {
            Log.d(BatterySampleFragment.TAG, "Hide battery warning");
            tvBatteryWarning.setVisibility(View.GONE);
        }
    }
 
Example #13
Source File: BatteryStatusView.java    From ExoVideoView with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
            status == BatteryManager.BATTERY_STATUS_FULL;

    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

    if (isCharging) {
        setImageResource(R.drawable.stat_sys_battery_charge);
    } else {
        setImageResource(R.drawable.stat_sys_battery);
    }
    setImageLevel(level);

}
 
Example #14
Source File: EasyBatteryMod.java    From easydeviceinfo with Apache License 2.0 6 votes vote down vote up
/**
 * Gets charging source.
 *
 * @return the charging source
 */
@ChargingVia
public final int getChargingSource() {
  Intent batteryStatus = getBatteryStatusIntent();
  int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);

  switch (chargePlug) {
    case BatteryManager.BATTERY_PLUGGED_AC:
      return ChargingVia.AC;
    case BatteryManager.BATTERY_PLUGGED_USB:
      return ChargingVia.USB;
    case BatteryManager.BATTERY_PLUGGED_WIRELESS:
      return ChargingVia.WIRELESS;
    default:
      return ChargingVia.UNKNOWN_SOURCE;
  }
}
 
Example #15
Source File: TypeTranslators.java    From under-the-hood with Apache License 2.0 6 votes vote down vote up
public static String translateBatteryStatus(int batteryStatus) {
    switch (batteryStatus) {
        case BatteryManager.BATTERY_STATUS_CHARGING:
            return "CHARGING";
        case BatteryManager.BATTERY_STATUS_DISCHARGING:
            return "DISCHARGING";
        case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
            return "NOT CHARGING";
        case BatteryManager.BATTERY_STATUS_FULL:
            return "FULL";
        case BatteryManager.BATTERY_STATUS_UNKNOWN:
            return "STATUS UNKNOWN";
        default:
            return "UNKNOWN (" + batteryStatus + ")";
    }
}
 
Example #16
Source File: BatteryReader.java    From daggerless-di-testing with Apache License 2.0 5 votes vote down vote up
public float getBatteryPercent() {
  IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
  Intent batteryStatus = context.registerReceiver(null, intentFilter);
  if (batteryStatus == null) {
    return 0;
  }
  int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
  int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
  return level * 100f / scale;
}
 
Example #17
Source File: BatteryStatusManager.java    From 365browser with Apache License 2.0 5 votes vote down vote up
BatteryStatusManager(BatteryStatusCallback callback) {
    // BatteryManager.EXTRA_PRESENT appears to be unreliable on Galaxy Nexus,
    // Android 4.2.1, it always reports false. See http://crbug.com/384348.
    this(callback, Build.MODEL.equals("Galaxy Nexus"),
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
                    ? new AndroidBatteryManagerWrapper(
                              (BatteryManager) ContextUtils.getApplicationContext()
                                      .getSystemService(Context.BATTERY_SERVICE))
                    : null);
}
 
Example #18
Source File: ReadBookActivity.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (readStatusBar != null) {
        if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) {
            readStatusBar.updateTime();
        } else if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            readStatusBar.updateBattery(level);
        }
    }
}
 
Example #19
Source File: InactivityTimer.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
        // 0 indicates that we're on battery
        boolean onBatteryNow = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) <= 0;
        if (onBatteryNow) {
            InactivityTimer.this.onActivity();
        } else {
            InactivityTimer.this.cancel();
        }
    }
}
 
Example #20
Source File: InactivityTimer.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent){
  if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
    // 0 indicates that we're on battery
    boolean onBatteryNow = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) <= 0;
    if (onBatteryNow) {
      InactivityTimer.this.onActivity();
    } else {
      InactivityTimer.this.cancel();
    }
  }
}
 
Example #21
Source File: InactivityTimerAssist.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (intent != null && Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
        // 0 indicates that we're on battery
        boolean isBatteryNow = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) <= 0;
        if (isBatteryNow) { // 属于非充电才进行记时
            InactivityTimerAssist.this.start();
        } else { // 充电中, 则不处理
            InactivityTimerAssist.this.cancel();
        }
    }
}
 
Example #22
Source File: InactivityTimer.java    From imsdk-android with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
        // 0 indicates that we're on battery
        boolean onBatteryNow = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) <= 0;
        if (onBatteryNow) {
            InactivityTimer.this.onActivity();
        } else {
            InactivityTimer.this.cancel();
        }
    }
}
 
Example #23
Source File: NeihanVideoPlayerController.java    From CrazyDaily with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
            BatteryManager.BATTERY_STATUS_UNKNOWN);
    if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
        // 充电中
        mBattery.setImageResource(R.drawable.battery_charging);
    } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
        // 充电完成
        mBattery.setImageResource(R.drawable.battery_full);
    } else {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
        int percentage = (int) (((float) level / scale) * 100);
        if (percentage <= 10) {
            mBattery.setImageResource(R.drawable.battery_10);
        } else if (percentage <= 20) {
            mBattery.setImageResource(R.drawable.battery_20);
        } else if (percentage <= 50) {
            mBattery.setImageResource(R.drawable.battery_50);
        } else if (percentage <= 80) {
            mBattery.setImageResource(R.drawable.battery_80);
        } else if (percentage <= 100) {
            mBattery.setImageResource(R.drawable.battery_100);
        }
    }
}
 
Example #24
Source File: Utils.java    From flickr-uploader with GNU General Public License v2.0 5 votes vote down vote up
public static boolean checkIfCharging() {
	try {
		IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		Intent batteryStatus = FlickrUploader.getAppContext().registerReceiver(null, ifilter);
		int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
		boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
		setCharging(isCharging);
	} catch (Throwable e) {
		LOG.error(ToolString.stack2string(e));
	}
	return charging;
}
 
Example #25
Source File: InactivityTimer.java    From BarcodeEye with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
        // 0 indicates that we're on battery
        boolean onBatteryNow = intent.getIntExtra(
                BatteryManager.EXTRA_PLUGGED, -1) <= 0;
        if (onBatteryNow) {
            InactivityTimer.this.onActivity();
        } else {
            InactivityTimer.this.cancel();
        }
    }
}
 
Example #26
Source File: BaseWatchFace.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static int getWearBatteryLevel(Context context) {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);//from BgSendQueue
    Intent batteryStatus = context.registerReceiver(null, ifilter);
    int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    if (level == -1 || scale == -1) {
        return 50;
    }
    else
        return (int) (((float) level / (float) scale) * 100.0f);
}
 
Example #27
Source File: DeviceBatteryMetricsCollectorTest.java    From Battery-Metrics with MIT License 5 votes vote down vote up
@Test
public void testInitialSnapshot() {
  ShadowSystemClock.setElapsedRealtime(5000);
  when(mContext.registerReceiver(
          Matchers.isNull(BroadcastReceiver.class), Matchers.any(IntentFilter.class)))
      .thenReturn(createBatteryIntent(BatteryManager.BATTERY_STATUS_CHARGING, 20, 100));
  DeviceBatteryMetrics metrics = new DeviceBatteryMetrics();
  DeviceBatteryMetricsCollector collector = new DeviceBatteryMetricsCollector(mContext);
  ShadowSystemClock.setElapsedRealtime(10000);
  collector.getSnapshot(metrics);
  verifySnapshot(metrics, 20, 0, 5000);
}
 
Example #28
Source File: InactivityTimer.java    From zxing with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
	if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
		// 0 indicates that we're on battery
		boolean onBatteryNow = intent.getIntExtra(
				BatteryManager.EXTRA_PLUGGED, -1) <= 0;
		if (onBatteryNow) {
			InactivityTimer.this.onActivity();
		} else {
			InactivityTimer.this.cancel();
		}
	}
}
 
Example #29
Source File: Utils.java    From Easer with GNU General Public License v3.0 5 votes vote down vote up
static boolean levelState(Intent intent, BatteryLevelUSourceData data) {
    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    double percent = level * 100.0 / scale;
    if (((BatteryLevelUSourceData.CustomLevel) data.level).inclusive) {
        return percent >= ((BatteryLevelUSourceData.CustomLevel) data.level).battery_level;
    } else {
        return percent > (((BatteryLevelUSourceData.CustomLevel) data.level).battery_level);
    }
}
 
Example #30
Source File: ShareGlucose.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public int getBatteryLevel() {
    Intent batteryIntent = mContext.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    if(level == -1 || scale == -1) {
        return 50;
    }
    return (int)(((float)level / (float)scale) * 100.0f);
}