Java Code Examples for android.content.Intent#ACTION_BATTERY_CHANGED

The following examples show how to use android.content.Intent#ACTION_BATTERY_CHANGED . 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: BatteryStats.java    From geopaparazzi with GNU General Public License v3.0 7 votes vote down vote up
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);
}
 
Example 2
Source File: ShootActivity.java    From TimeLapse with MIT License 6 votes vote down vote up
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) + "%";
}
 
Example 3
Source File: DeviceIdleController.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@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;
    }
}
 
Example 4
Source File: BatteryPresenter.java    From microbit with Apache License 2.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example 5
Source File: BatteryStatus.java    From JayPS-AndroidApp with MIT License 5 votes vote down vote up
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;
}
 
Example 6
Source File: EddystoneTLM.java    From beacons-android with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 7
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 8
Source File: BatteryMonitor.java    From JPPF with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 9
Source File: BatteryState.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/** 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);
}
 
Example 10
Source File: BaseWatchFace.java    From xDrip-plus 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 11
Source File: ViewUtils.java    From native-navigation with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 12
Source File: OfflinePageUtils.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/** 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);
}
 
Example 13
Source File: PlayerTopControl.java    From android-jungle-mediaplayer with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 14
Source File: BatteryService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 15
Source File: PowerMonitor.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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);
    }
}
 
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: BatteryUtil.java    From HaoReader with GNU General Public License v3.0 4 votes vote down vote up
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;
}
 
Example 18
Source File: LockDeviceService.java    From SecondScreen with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 19
Source File: AndroidBatteryState.java    From QtAndroidTools with MIT License 4 votes vote down vote up
public AndroidBatteryState(Activity ActivityInstance)
{
    mBatteryStateChangeReceiver = new BatteryStateChangeReceiver();
    mBatteryStateFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    mActivityInstance = ActivityInstance;
}
 
Example 20
Source File: Utils.java    From haven with GNU General Public License v3.0 3 votes vote down vote up
/**
 * 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);
}