下面列出了android.content.Intent#ACTION_BATTERY_CHANGED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void onCreate() {
BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
int scale = -1;
int level = -1;
int voltage = -1;
int temp = -1;
@Override
public void onReceive(Context context, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
Log.e("BatteryManager", "level is " + level + "/" + scale + ", temp is " + temp + ", voltage is " + voltage);//NON-NLS
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryReceiver, filter);
}
@Override public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case ConnectivityManager.CONNECTIVITY_ACTION: {
updateConnectivityState(intent);
} break;
case Intent.ACTION_BATTERY_CHANGED: {
synchronized (DeviceIdleController.this) {
int plugged = intent.getIntExtra("plugged", 0);
updateChargingLocked(plugged != 0);
}
} break;
case Intent.ACTION_PACKAGE_REMOVED: {
if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Uri data = intent.getData();
String ssp;
if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
removePowerSaveWhitelistAppInternal(ssp);
}
}
} break;
}
}
private String getBatteryPercentage()
{
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL ||
chargePlug == BatteryManager.BATTERY_PLUGGED_USB ||
chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
String s = "";
if(isCharging)
s = "c ";
return s + (int)(level / (float)scale * 100) + "%";
}
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);
}
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;
}
public static void create(Context context) {
if (sInstance == null) {
sInstance = LazyHolder.INSTANCE;
ActivityStatus.registerStateListener(sInstance);
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatusIntent = context.registerReceiver(null, ifilter);
onBatteryChargingChanged(batteryStatusIntent);
}
}
private void sendBatteryChangedIntentLocked() {
// Pack up the values and broadcast them to everyone
final Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
| Intent.FLAG_RECEIVER_REPLACE_PENDING);
int icon = getIconLocked(mHealthInfo.batteryLevel);
intent.putExtra(BatteryManager.EXTRA_SEQUENCE, mSequence);
intent.putExtra(BatteryManager.EXTRA_STATUS, mHealthInfo.batteryStatus);
intent.putExtra(BatteryManager.EXTRA_HEALTH, mHealthInfo.batteryHealth);
intent.putExtra(BatteryManager.EXTRA_PRESENT, mHealthInfo.batteryPresent);
intent.putExtra(BatteryManager.EXTRA_LEVEL, mHealthInfo.batteryLevel);
intent.putExtra(BatteryManager.EXTRA_BATTERY_LOW, mSentLowBatteryBroadcast);
intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE);
intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon);
intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType);
intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mHealthInfo.batteryVoltage);
intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mHealthInfo.batteryTemperature);
intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mHealthInfo.batteryTechnology);
intent.putExtra(BatteryManager.EXTRA_INVALID_CHARGER, mInvalidCharger);
intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_CURRENT, mHealthInfo.maxChargingCurrent);
intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_VOLTAGE, mHealthInfo.maxChargingVoltage);
intent.putExtra(BatteryManager.EXTRA_CHARGE_COUNTER, mHealthInfo.batteryChargeCounter);
if (DEBUG) {
Slog.d(TAG, "Sending ACTION_BATTERY_CHANGED. scale:" + BATTERY_SCALE
+ ", info:" + mHealthInfo.toString());
}
mHandler.post(() -> ActivityManager.broadcastStickyIntent(intent, UserHandle.USER_ALL));
}
public void create(int resId) {
View.inflate(getContext(), resId, this);
findViewById(R.id.player_back_zone).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mListener.onBackBtnClicked();
}
});
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
getContext().registerReceiver(mBatteryReceiver, filter);
updateSystemTime(false);
}
/** Returns the current device conditions. May be overridden for testing. */
protected DeviceConditions getDeviceConditionsImpl(Context context) {
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
// Note this is a sticky intent, so we aren't really registering a receiver, just getting
// the sticky intent. That means that we don't need to unregister the filter later.
Intent batteryStatus = context.registerReceiver(null, filter);
if (batteryStatus == null) return null;
// Get the connection type from chromium's internal object.
int connectionType = NetworkChangeNotifier.getInstance().getCurrentConnectionType();
// Sometimes the NetworkConnectionNotifier lags the actual connection type, especially when
// the GCM NM wakes us from doze state. If we are really connected, report the connection
// type from android.
if (connectionType == ConnectionType.CONNECTION_NONE) {
// Get the connection type from android in case chromium's type is not yet set.
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (isConnected) {
connectionType = convertAndroidNetworkTypeToConnectionType(activeNetwork.getType());
}
}
return new DeviceConditions(
isPowerConnected(batteryStatus), batteryPercentage(batteryStatus), connectionType);
}
/**
* https://developer.android.com/training/monitoring-device-state/battery-monitoring.html
*/
public static int getBatteryState(Context context) {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
if (batteryStatus == null) {
return BatteryManager.BATTERY_STATUS_UNKNOWN;
}
return batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
}
@Override
public void start() {
if(!isRegistered) {
isRegistered = true;
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
application.registerReceiver(batteryReceiver, filter);
if(informationPlugin != null) {
CmdArg cmd = new CmdArg(0, "Registered Battery.");
informationPlugin.sendReplyCommand(PluginService.INFORMATION, cmd);
}
}
}
/** Creates a new BatteryState using data from the given Context. */
public static BatteryState get(Context context) {
boolean powerConnected = false;
Float level = null;
final IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
final Intent batteryStatusIntent = context.registerReceiver(null, ifilter);
if (batteryStatusIntent != null) {
powerConnected = isPowerConnected(batteryStatusIntent);
level = getLevel(batteryStatusIntent);
}
return new BatteryState(level, powerConnected);
}
/**
* Get the percentage of battery charge.
* @return the battery charge in % as a float value.
*/
private int updateChargePct() {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
currentLevel.set((int) (100f * level / (float) scale));
return currentLevel.get();
}
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;
}
@Override
public Advertiser createAdvertiser(BleService service) {
byte[] data = new byte[12];
if (null != service) {
ByteBuffer buffer = ByteBuffer.wrap(data);
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent stickyIntent = service.registerReceiver(null, intentFilter);
if (null != stickyIntent) {
mBatteryVoltage = (short) stickyIntent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
buffer.putShort(mBatteryVoltage);
mBatteryTemperature = stickyIntent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
// (int * 10) to fixed point 8.8
buffer.putShort((short) (mBatteryTemperature / 10 << 8 | mBatteryTemperature % 10 * 256 / 10));
mEstimatedPDUCount = (int) service.updateEstimatedPDUCount();
buffer.putInt(mEstimatedPDUCount);
mPowerOnTime = (int) service.getPowerOnTime();
buffer.putInt(mPowerOnTime / 100);
}
}
return new EddystoneAdvertiser(this, EddystoneAdvertiser.FRAME_TLM, data, 0, data.length);
}
public static int getBatteryLevel(Context context) {
int batteryLevel = -1;
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
int rawlevel = batteryStatus.getIntExtra("level", -1);
int scale = batteryStatus.getIntExtra("scale", -1);
if (rawlevel >= 0 && scale > 0) {
batteryLevel = (rawlevel * 100) / scale;
}
//Log.d(TAG, "battery rawlevel:" + rawlevel + " scale:" + scale + " batteryLevel:" + batteryLevel);
return batteryLevel;
}
@Override
protected void onHandleIntent(Intent intent) {
super.onHandleIntent(intent);
// Close the notification drawer
Intent closeDrawer = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDrawer);
// Determine current charging status
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, ifilter);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
// Get current UI mode
UiModeManager mUiModeManager = (UiModeManager) getSystemService(Context.UI_MODE_SERVICE);
int uiMode = mUiModeManager.getCurrentModeType();
// Determine current dock state, based on the current UI mode
boolean isDocked;
switch(uiMode) {
case Configuration.UI_MODE_TYPE_DESK:
isDocked = true;
break;
case Configuration.UI_MODE_TYPE_CAR:
isDocked = true;
break;
default:
isDocked = false;
}
// In order to ensure that the device locks itself when the following code is run,
// we need to temporarily set the lock screen lock after timeout value.
// For a smooth transition into the daydream, we set this value to one millisecond,
// locking the device at the soonest opportunity after the transition completes.
int timeout = Settings.Secure.getInt(getContentResolver(), "lock_screen_lock_after_timeout", 5000);
if(timeout != 1) {
SharedPreferences prefMain = U.getPrefMain(this);
SharedPreferences.Editor editor = prefMain.edit();
editor.putInt("timeout", Settings.Secure.getInt(getContentResolver(), "lock_screen_lock_after_timeout", 5000));
editor.apply();
U.runCommand(this, U.timeoutCommand + "1");
}
// Schedule TimeoutService to reset lock screen timeout to original value
Intent timeoutService = new Intent(this, TimeoutService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 123456, timeoutService, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, pendingIntent);
// If Daydreams is enabled and the device is charging, then lock the device by launching the daydream.
if(isCharging
&& !U.castScreenActive(this)
&& Settings.Secure.getInt(getContentResolver(), "screensaver_enabled", 0) == 1
&& ((Settings.Secure.getInt(getContentResolver(), "screensaver_activate_on_dock", 0) == 1 && isDocked)
|| Settings.Secure.getInt(getContentResolver(), "screensaver_activate_on_sleep", 0) == 1)) {
// Send intent to launch the current daydream manually
Intent lockIntent = new Intent(Intent.ACTION_MAIN);
lockIntent.setComponent(ComponentName.unflattenFromString("com.android.systemui/.Somnambulator"));
lockIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(lockIntent);
} catch (ActivityNotFoundException e) { /* Gracefully fail */ }
} else
// Otherwise, send a power button keystroke to lock the device normally
U.lockDevice(this);
}
public static int getLevel(Context context) {
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, iFilter);
return batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
}
public AndroidBatteryState(Activity ActivityInstance)
{
mBatteryStateChangeReceiver = new BatteryStateChangeReceiver();
mBatteryStateFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
mActivityInstance = ActivityInstance;
}
/**
* Get the battery level from the device, from official docs:
* https://developer.android.com/training/monitoring-device-state/battery-monitoring#MonitorLevel
* @param context
* @return an integer corresponding to the battery percentage without any symbols
*/
public static int getBatteryPercentage(Context context) {
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, iFilter);
int level = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
int scale = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;
float batteryPct = level / (float) scale;
return (int) (batteryPct * 100);
}