下面列出了android.content.ReceiverCallNotAllowedException#android.os.BatteryManager 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
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);
}
@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);
}
}
}
}
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);
}
}
});
}
}
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);
}
}
@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);
}
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 + ")";
}
}
/**
* 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;
}
}
/**
* 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;
}
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;
}
@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);
}
}
}
/**
* 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;
}
/**
* @see #isPlugged(android.content.Context)
* @see #isPlugged(android.content.Intent)
*/
@SuppressLint("InlinedApi")
public static int getBatteryLevel(@Nullable Intent intent) {
if (intent == null) {
return 100;
}
final int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
final int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
return level * 100 / scale;
}
public static void logAllBatteryValues(final Context context) {
BatteryManager manager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
LogUtils.logI("Battery Voltage", "v: " + getBatteryVoltage(context));
if (Build.VERSION.SDK_INT >= 21) {
LogUtils.logI("[API] Battery Capacity", "v: " +
manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY));
LogUtils.logI("[API] Battery Charge Counter", "v: " +
manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER));
LogUtils.logI("[API] Battery Energy Counter", "v: " +
manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER));
LogUtils.logI("[API] Battery Current Average", "v: " +
manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE));
LogUtils.logI("[API] Battery Current Now", "v: " +
manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW));
}
LogUtils.logI("Battery Capacity", "v: " +
getBatteryPropertyLegacy(Config.BATTERY_CAPACITY));
LogUtils.logI("Battery Charge Counter", "v: " +
getBatteryPropertyLegacy(Config.BATTERY_CHARGE_FULL));
LogUtils.logI("Battery Charge Counter (Design)", "v: " +
getBatteryPropertyLegacy(Config.BATTERY_CHARGE_FULL_DESIGN));
LogUtils.logI("Battery Energy Counter", "v: " +
getBatteryPropertyLegacy(Config.BATTERY_ENERGY_FULL));
LogUtils.logI("Battery Energy Counter (Design)", "v: " +
getBatteryPropertyLegacy(Config.BATTERY_ENERGY_FULL_DESIGN));
LogUtils.logI("Battery Current Now", "v: " +
getBatteryPropertyLegacy(Config.BATTERY_CURRENT_NOW));
LogUtils.logI("Battery Current Now (2)", "v: " +
getBatteryCurrentNowLegacy());
LogUtils.logI("Battery Energy Now", "v: " +
getBatteryPropertyLegacy(Config.BATTERY_ENERGY_NOW));
// Reflections
LogUtils.logI("Actual Battery Capacity", "v: " + getBatteryDesignCapacity(context));
}
@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();
}
}
}
@Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int maxValue = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int chargedPct = (level * 100) / maxValue;
updateBatteryCondition(chargedPct);
}
public int getBatteryLevel() {
Intent batteryIntent = mContext.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
if (batteryIntent != null) {
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);
} else return 50;
}
/**
* Checks whether or not the device is currently plugged in and charging, or null if unknown.
*
* @return whether or not the device is currently plugged in and charging, or null if unknown
*/
private @Nullable Boolean isCharging(final @NotNull Intent batteryIntent) {
try {
int plugged = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
return plugged == BatteryManager.BATTERY_PLUGGED_AC
|| plugged == BatteryManager.BATTERY_PLUGGED_USB;
} catch (Exception e) {
logger.log(SentryLevel.ERROR, "Error getting device charging state.", e);
return null;
}
}
@Override
public void onReceive(BatteryIconData icon, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
int iconLevel = (int) (((float) level / scale) * 6) + 1;
if (status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL)
iconLevel += 7;
icon.onIconUpdate(iconLevel);
icon.onTextUpdate(String.valueOf((int) (((double) level / scale) * 100)) + "%");
}
/**
* 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;
// }
}
@SuppressWarnings("ConstantConditions")
private static int getBatteryLevel() {
final Intent batteryIntent = xdrip.getAppContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
try {
final int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
final int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (level == -1 || scale == -1) {
return -1;
}
return (int) (((float) level / (float) scale) * 100.0f);
} catch (NullPointerException e) {
return -1;
}
}
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;
}
}
@Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean charging = plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
currentBattery = level;
Utils.logDebug(MAIN_SERVICE_LOG_TAG, "Battery level " + level);
if (batteryTV != null)
batteryTV.setText(String.valueOf(level) + "%");
if (batteryIV != null) {
int res;
if (charging)
res = R.drawable.ic_battery_charging;
else {
if (level > 90)
res = R.drawable.ic_battery_full;
else if (level > 70)
res = R.drawable.ic_battery_90;
else if (level > 50)
res = R.drawable.ic_battery_60;
else if (level > 30)
res = R.drawable.ic_battery_30;
else if (level > 20)
res = R.drawable.ic_battery_20;
else if (level > 0)
res = R.drawable.ic_battery_alert;
else
res = R.drawable.ic_battery_unknown;
}
batteryIV.setImageResource(res);
}
}
@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();
}
}
}
/**
* Gets battery voltage.
*
* @return the battery voltage
*/
public final int getBatteryVoltage() {
int volt = 0;
Intent batteryStatus = getBatteryStatusIntent();
if (batteryStatus != null) {
volt = batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
}
return volt;
}
private String getBatteryStatus(Intent intent) {
// Are we charging / charged?
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
mIsCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
lastTemperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, Integer.MIN_VALUE);
ReceiverStorage.getInstance().setBatteryTemperature(getLastTemperature());
// How are we charging?
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
ChargingType chargingType = ChargingType.getType(chargePlug);
String chargeSource = chargingType != null ? chargingType.toString() : botService.getString(R.string.unknown);
return mIsCharging ? String.format(botService.getString(R.string.charging), chargeSource) : botService.getString(R.string.discharging);
}
private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
// Don't wake when powered unless configured to do so.
if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
return false;
}
// Don't wake when undocked from wireless charger.
// See WirelessChargerDetector for justification.
if (wasPowered && !mIsPowered
&& oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
return false;
}
// Don't wake when docked on wireless charger unless we are certain of it.
// See WirelessChargerDetector for justification.
if (!wasPowered && mIsPowered
&& mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
&& !dockedOnWirelessCharger) {
return false;
}
// If already dreaming and becoming powered, then don't wake.
if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
return false;
}
// Don't wake while theater mode is enabled.
if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) {
return false;
}
// On Always On Display, SystemUI shows the charging indicator
if (mAlwaysOnEnabled && mWakefulness == WAKEFULNESS_DOZING) {
return false;
}
// Otherwise wake up!
return true;
}
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) {
Slog.d(TAG, "onReceive: " + intent);
}
switch (intent.getAction()) {
case Intent.ACTION_SCREEN_ON:
case Intent.ACTION_SCREEN_OFF:
if (!isEnabled()) {
updateBatterySavingStats();
return; // No need to send it if not enabled.
}
// Don't send the broadcast, because we never did so in this case.
mHandler.postStateChanged(/*sendBroadcast=*/ false,
REASON_INTERACTIVE_CHANGED);
break;
case Intent.ACTION_BATTERY_CHANGED:
synchronized (mLock) {
mIsPluggedIn = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0);
}
// Fall-through.
case PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED:
case PowerManager.ACTION_LIGHT_DEVICE_IDLE_MODE_CHANGED:
updateBatterySavingStats();
break;
}
}
public static int getBatteryLevel(Context context) {
Intent batteryIntent = context.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);
}
@Override
public void onReceive(Context context, Intent intent) {
mCharging = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0);
synchronized (mLock) {
if (mSystemReady) {
updateLocked(0, 0);
}
}
}