Java 类android.os.BatteryManager 实例源码

项目:GitHub    文件:IjkPlayerView.java   
@Override
public void onReceive(Context context, Intent intent) {
    // 接收电量变化信息
    if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
        int level = intent.getIntExtra("level", 0);
        int scale = intent.getIntExtra("scale", 100);
        // 电量百分比
        int curPower = level * 100 / scale;
        int status = intent.getIntExtra("status", BatteryManager.BATTERY_HEALTH_UNKNOWN);
        // SecondaryProgress 用来展示低电量,Progress 用来展示正常电量
        if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
            mPbBatteryLevel.setSecondaryProgress(0);
            mPbBatteryLevel.setProgress(curPower);
            mPbBatteryLevel.setBackgroundResource(R.mipmap.ic_battery_charging);
        } else if (curPower < BATTERY_LOW_LEVEL) {
            mPbBatteryLevel.setProgress(0);
            mPbBatteryLevel.setSecondaryProgress(curPower);
            mPbBatteryLevel.setBackgroundResource(R.mipmap.ic_battery_red);
        } else {
            mPbBatteryLevel.setSecondaryProgress(0);
            mPbBatteryLevel.setProgress(curPower);
            mPbBatteryLevel.setBackgroundResource(R.mipmap.ic_battery);
        }
    }
}
项目:JobSchedulerCompat    文件:DeviceTestUtils.java   
@SuppressWarnings("deprecation")
public static void setCharging(Context context, boolean charging) {
    Intent chargingIntent = new Intent(Intent.ACTION_BATTERY_CHANGED);
    if (charging) {
        chargingIntent.putExtra(BatteryManager.EXTRA_PLUGGED, BatteryManager.BATTERY_PLUGGED_AC);
    }
    context.sendStickyBroadcast(chargingIntent);
}
项目:MyFire    文件:InactivityTimer.java   
@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();
        }
    }
}
项目:LuaViewPlayground    文件:InactivityTimer.java   
@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();
        }
    }
}
项目:buildAPKsApps    文件:Main.java   
private void batteryLevelUpdater()
{
    batteryLevelReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            //context.unregisterReceiver(this);
            int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            int level = -1;
            if (rawlevel >= 0 && scale > 0) {
                level = (rawlevel * 100) / scale;
            }
            mBatteryLevelView.setLevel(level);
        }
    };
    batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
项目:iSPY    文件:TrackerService.java   
private float getBatteryLevel() {
    Intent batteryStatus = registerReceiver(null,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int batteryLevel = -1;
    int batteryScale = 1;
    if (batteryStatus != null) {
        batteryLevel = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, batteryLevel);
        batteryScale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, batteryScale);
    }
    return batteryLevel / (float) batteryScale * 100;
}
项目:thingplug-sdk-android    文件:SensorListener.java   
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction() == Intent.ACTION_BATTERY_CHANGED) {
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        float temperature = ((float) intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)) / 10;
        float chargeLevel = ((float) (level * 100)) / scale;

        for (SensorInfo sensorInfo : sensorInfos) {
            if (sensorInfo.getType() == SensorType.BATTERY) {
                sensorInfo.setValues(new float[]{temperature, chargeLevel});
                break;
            }
        }
    }
}
项目:Xndroid    文件:XndroidReceiver.java   
private void handleBattery(Intent intent){
    int level=intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
    int scale=intent.getIntExtra(BatteryManager.EXTRA_SCALE,0);
    int levelPercent = (int)(((float)level / scale) * 100);
    boolean charging = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
            BatteryManager.BATTERY_STATUS_UNKNOWN) == BatteryManager.BATTERY_STATUS_CHARGING;
    if(levelPercent < BATTERY_LOW_LIMIT && !charging)
        AppModel.sDevBatteryLow = true;
    else
        AppModel.sDevBatteryLow = false;
    LogUtils.i("battery:" + level +"%, BatteryLow=" + AppModel.sDevBatteryLow);
}
项目:GitHub    文件:CrashDetails.java   
/**
 * Returns the current device battery level.
 */
static String getBatteryLevel(Context context) {
    try {
        Intent batteryIntent = context.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);

            // Error checking that probably isn't needed but I added just in case.
            if (level > -1 && scale > 0) {
                return Float.toString(((float) level / (float) scale) * 100.0f);
            }
        }
    }
    catch(Exception e){
        if (Countly.sharedInstance().isLoggingEnabled()) {
            Log.i(Countly.TAG, "Can't get batter level");
        }
    }

    return null;
}
项目:gpstracker-android    文件:BatteryRecorder.java   
private void recordBatteryLevel() {
    Log.i(TAG, "Record battery level");

    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = mContext.registerReceiver(null, ifilter);

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

    float batteryPct = (level / (float) scale) * 100;
    mTelemetry.write(Telemetry.BATTERY_TAG, String.valueOf(batteryPct));
}
项目:snu-artoon    文件:MainActivity.java   
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
        int remain = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        String remainString = Integer.toString(remain) + "%";
        currentStatus.setText(remainString);

        int plugIn = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
        switch (plugIn) {
            case 0:
                adapterStatus.setText("No Connection");
                break;

            case BatteryManager.BATTERY_PLUGGED_AC:
                adapterStatus.setText("Adapter Connected");
                break;

            case BatteryManager.BATTERY_PLUGGED_USB:
                adapterStatus.setText("USB Connected");
                break;
        }
    }
}
项目:labtablet    文件:FieldModeActivity.java   
private void registerBatInforReceiver() {
    mBatInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0, Intent intent) {
            if ((System.currentTimeMillis() - lastUpdateSensorTemperature) < Utils.SAMPLE_MILLIS) {
                return;
            }
            int temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) / 10;
            temperature_value = "" + temperature;
            bt_temperature_sample.setEnabled(true);
            bt_temperature_sample.setText(temperature_value + getResources().getString(R.string.battery_temp));
            lastUpdateSensorTemperature = System.currentTimeMillis();
        }
    };
    registerReceiver(mBatInfoReceiver,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
项目:WearVibrationCenter    文件:PhoneCommandListener.java   
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean filterCommand(InterruptionCommand command) {
    if (command.shouldNotVibrateOnCharger()) {
        Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        boolean pluggedIn = batteryIntent != null && batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;
        if (pluggedIn) {
            Timber.d("Filter - Charger!");
            return false;
        }
    }

    if (command.shouldNotVibrateInTheater() &&
            WatchUtils.isWatchInTheaterMode(this)) {
        Timber.d("Filter - Theater mode!");
        return false;
    }

    return true;
}
项目:LucaHome-AndroidApplication    文件:BottomInfoViewController.java   
@Override
public void onReceive(Context context, Intent intent) {
    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    if (level != -1) {
        _batteryTextView.setText(String.format(Locale.getDefault(), "%d %%", level));
        _batteryAlarmView.setVisibility(View.VISIBLE);
        if (level > BatterySocketController.UPPER_BATTERY_LIMIT) {
            _batteryAlarmView.setBackgroundResource(R.drawable.circle_green);
        } else if (level < BatterySocketController.LOWER_BATTERY_LIMIT) {
            _batteryAlarmView.setBackgroundResource(R.drawable.circle_red);
        } else {
            _batteryAlarmView.setBackgroundResource(R.drawable.circle_green);
        }
    } else {
        _batteryTextView.setText("Error!");
        _batteryAlarmView.setVisibility(View.GONE);
    }
}
项目:Lantern-sdk    文件:RylaInstrumentation.java   
private float getBatteryPercent() {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = RYLA.getInstance().getContext().registerReceiver(null, ifilter);

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

    return level / (float)scale * 100;
}
项目:DeviceInfo    文件:BatteryFragment.java   
@Override
public void onReceive(Context c, Intent intent) {

    deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

    level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
    health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0);
    icon_small = intent.getIntExtra(BatteryManager.EXTRA_ICON_SMALL, 0);

    plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
    present = intent.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT);

    scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
    status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);

    technology = intent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
    temperature = (intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) / 10);

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

    try {
        getBatteryInfo();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}
项目:home-assistant-Android    文件:LocationUpdateReceiver.java   
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);
}
项目:home-assistant-Android    文件:LocationUpdateReceiver.java   
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);
}
项目:homeDash    文件:SensorReader.java   
public  void getBatteryReading(SensorDataListener listener){

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

        int batteryStatusIntExtra = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = batteryStatusIntExtra == BatteryManager.BATTERY_STATUS_CHARGING ||
                batteryStatusIntExtra == BatteryManager.BATTERY_STATUS_FULL;

        int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

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

        float batteryPct = level / (float)scale;

        Log.i(TAG, "AC connected: "+acCharge);
        Log.i(TAG, "USB connected: "+usbCharge);
        Log.i(TAG, "Battery charging: "+ isCharging);
        Log.i(TAG, "Battery Level: "+ batteryPct);

        ArrayMap<String, String> map = new ArrayMap<>(3);
        map.put(SENSOR, "Battery");
        map.put(VALUE, Integer.toString(level));
        map.put(UNIT, BATTERYSENSOR_UNIT);
        map.put("charging", Boolean.toString(isCharging));
        map.put("acPlugged", Boolean.toString(acCharge));
        map.put("usbPlugged", Boolean.toString(usbCharge));
        listener.sensorData(map);
    }
项目:LucaHome-MediaServer    文件:InfoViewController.java   
@Override
public void onReceive(Context context, Intent intent) {
    if (!_screenEnabled) {
        _logger.Debug("Screen is not enabled!");
        return;
    }

    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
    _batteryValueTextView.setText(String.format("%s%%", level));

    if (level > BAT_LVL_LOW) {
        _batteryAlarmView.setBackgroundResource(R.drawable.circle_green);
    } else if (level <= BAT_LVL_LOW && level > BAT_LVL_CRITICAL) {
        _batteryAlarmView.setBackgroundResource(R.drawable.circle_yellow);
    } else {
        _batteryAlarmView.setBackgroundResource(R.drawable.circle_red);
    }
}
项目:BatteryAlert    文件:BatteryReceiver.java   
@Override
public void onReceive(Context context, Intent intent) {
    int alertValue = PreferenceManager.getDefaultSharedPreferences(context).getInt(MainActivity.KEY_BATTERY_PERCENT, 20);

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

    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_AC;
    float value = (level * 100f) / scale;

    if (!isCharging && (int) value == alertValue) {
        ((Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE)).vibrate(3000);
        Toast.makeText(context, String.format(context.getString(R.string.msg_low_battery), (int) value), Toast.LENGTH_LONG).show();
    }
}
项目:device-info    文件:BatteryViewImpl.java   
private void setStatus(int statusValue) {
    String status;

    switch (statusValue) {
        case BatteryManager.BATTERY_STATUS_CHARGING:
            status = getString(R.string.battery_status_charging);
            break;
        case BatteryManager.BATTERY_STATUS_DISCHARGING:
            status = getString(R.string.battery_status_discharging);
            break;
        case BatteryManager.BATTERY_STATUS_FULL:
            status = getString(R.string.battery_status_full);
            break;
        case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
            status = getString(R.string.battery_status_not_charging);
            break;
        case BatteryManager.BATTERY_STATUS_UNKNOWN:
        default:
            status = getString(R.string.battery_status_unknown);
    }

    mViewStatus.setValue(status);
    mBatteryInfo.setStatus(status);
}
项目:device-info    文件:BatteryStateProviderImpl.java   
@Override
public void onReceive(Context context, Intent intent) {
    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, INVALID);
    int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, INVALID);
    int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, INVALID);
    int source = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, INVALID);
    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
    String type = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY);
    double temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, INVALID) / 10.0;
    int voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, INVALID);

    mBatteryState.setLevel(level);
    mBatteryState.setHealth(health);
    mBatteryState.setCharging(isCharging);
    mBatteryState.setStatus(status);
    mBatteryState.setSource(source);
    mBatteryState.setCapacity(getCapacity());
    mBatteryState.setType(type);
    mBatteryState.setTemperature(temperature);
    mBatteryState.setVoltage(voltage);

    mListener.onBatteryStateChanged(mBatteryState);
}
项目:device-info    文件:BatteryStateProviderImplTest.java   
@Test
public void testOnReceive() throws Exception {
    BatteryStateProviderListener mockListener = mock(BatteryStateProviderListener.class);
    mProvider.setListener(mockListener);
    Intent mockIntent = mock(Intent.class);
    when(mockIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, INVALID)).thenReturn(LEVEL);
    when(mockIntent.getIntExtra(BatteryManager.EXTRA_HEALTH, INVALID)).thenReturn(HEALTH);
    when(mockIntent.getIntExtra(BatteryManager.EXTRA_STATUS, INVALID)).thenReturn(STATUS);
    when(mockIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, INVALID)).thenReturn(POWER_SOURCE);
    when(mockIntent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY)).thenReturn(TYPE);
    when(mockIntent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, INVALID)).thenReturn(TEMPERATURE);
    when(mockIntent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, INVALID)).thenReturn(VOLTAGE);

    mProvider.onReceive(mMockContext, mockIntent);

    verify(mMockBatteryState).setLevel(LEVEL);
    verify(mMockBatteryState).setHealth(HEALTH);
    verify(mMockBatteryState).setCharging(false);
    verify(mMockBatteryState).setStatus(STATUS);
    verify(mMockBatteryState).setSource(POWER_SOURCE);
    verify(mMockBatteryState).setCapacity(INVALID);
    verify(mMockBatteryState).setType(TYPE);
    verify(mMockBatteryState).setTemperature(TEMPERATURE_EXPECTED);
    verify(mMockBatteryState).setVoltage(VOLTAGE);
    verify(mockListener).onBatteryStateChanged(mMockBatteryState);
}
项目:offloading-framework-android    文件:DeviceProfiler.java   
/**
 * Computes the battery level by registering a receiver to the intent triggered by a battery
 * status/level change.
 */
public static void trackBatteryLevel() {
  if (batteryTrackingOn == false) {
    batteryLevelReceiver = new BroadcastReceiver() {
      public void onReceive(Context context, Intent intent) {
        // context.unregisterReceiver(this);
        int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        int level = -1;
        if (rawlevel >= 0 && scale > 0) {
          level = (rawlevel * 100) / scale;
        }
        Log.d(TAG,
            "Battery level - " + level + ", voltage - " + SysClassBattery.getCurrentVoltage());
        batteryLevel = level;
      }
    };
    IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    context.registerReceiver(batteryLevelReceiver, batteryLevelFilter);
    synchronized (batteryTrackingSyncObject) {
      batteryTrackingOn = true;
    }
  }
}
项目:batteryhub    文件:DataEstimator.java   
public void getCurrentStatus(final Context context) {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

    try {
        Intent batteryStatus = context.registerReceiver(null, ifilter);

        if (batteryStatus != null) {
            level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            mHealth = batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH, 0);
            plugged = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
            present = batteryStatus.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT);
            status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
            technology = batteryStatus.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
            temperature = (float) (batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) / 10);
            voltage = (float) (batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0) / 1000);
        }
    } catch (ReceiverCallNotAllowedException e) {
        LOGE(TAG, "ReceiverCallNotAllowedException from Notification Receiver?");
        e.printStackTrace();
    }
}
项目:android-xmpp-iot-demo    文件:XmppIotThing.java   
private void addBatteryStateTo(Collection<IoTDataField> dataFields) {
    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent intent = mContext.registerReceiver(null, intentFilter);

    int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
    IoTDataField.BooleanField chargingField = new IoTDataField.BooleanField("charging", isCharging);
    dataFields.add(chargingField);

    int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    boolean isPlugged = plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS;
    IoTDataField.BooleanField pluggedField = new IoTDataField.BooleanField("plugged", isPlugged);
    dataFields.add(pluggedField);

    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    float batteryPercent = level / (float) scale;
    // Scale to percents.
    batteryPercent *= 100;
    IoTDataField.IntField batteryPercentField = new IoTDataField.IntField("batteryPrecent", (int) batteryPercent);
    dataFields.add(batteryPercentField);
}
项目:under-the-hood    文件:TypeTranslators.java   
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 + ")";
    }
}
项目:under-the-hood    文件:TypeTranslators.java   
public static String translateBatteryHealth(int batteryHealth) {
    switch (batteryHealth) {
        case BatteryManager.BATTERY_HEALTH_UNKNOWN:
            return "UNKNOWN HEALTH";
        case BatteryManager.BATTERY_HEALTH_GOOD:
            return "GOOD";
        case BatteryManager.BATTERY_HEALTH_OVERHEAT:
            return "OVERHEAT";
        case BatteryManager.BATTERY_HEALTH_DEAD:
            return "DEAD";
        case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
            return "OVER VOLTAGE";
        case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
            return "UNSPECIFIED FAILURE";
        case BatteryManager.BATTERY_HEALTH_COLD:
            return "COLD";
        default:
            return "UNKNOWN (" + batteryHealth + ")";
    }
}
项目:TUI-ConsoleLauncher    文件:Tuils.java   
@Override
public void onReceive(Context context, Intent intent) {
    if(batteryUpdate == null) return;

    switch (intent.getAction()) {
        case Intent.ACTION_BATTERY_CHANGED:
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            batteryUpdate.update(level);
            break;
        case Intent.ACTION_POWER_CONNECTED:
            batteryUpdate.onCharging();
            break;
        case Intent.ACTION_POWER_DISCONNECTED:
            batteryUpdate.onNotCharging();
            break;
    }
}
项目:Device-Explorer    文件:Content.java   
public String getContents() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb, Locale.US);
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = sContext.registerReceiver(null, ifilter);
    f.format("present: %b\n", batteryStatus.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false));
    f.format("technology: %s\n", batteryStatus.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY));
    f.format("status: %d\n", batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1));
    f.format("plugged: %d\n", batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1));
    f.format("health: %d\n", batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH, -1));
    f.format("level: %d of %d\n", batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1),
            batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1));
    f.format("temperature: %d\n", batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1));
    f.format("voltage: %d\n", batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1));
    return sb.toString();
}
项目:Status    文件:BatteryIconData.java   
@Override
public void register() {
    Intent intent = getContext().registerReceiver(receiver, getIntentFilter());

    if (intent != null) {
        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;

        onDrawableUpdate(iconLevel);

        if (hasText())
            onTextUpdate(String.valueOf((int) (((double) level / scale) * 100)) + "%");
    }
}
项目:TheLearningLock    文件:StatusBar.java   
private void setBatteryPct() {
    // Sets battery percentage
    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);
    int batteryPct = Math.round(level / (float) scale * 100);
    int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    boolean charging = chargePlug == BatteryManager.BATTERY_PLUGGED_USB || chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    // Text
    ((TextView) statusBar.findViewById(R.id.battery_percentage)).setText(Integer.toString(batteryPct) + "%");
    // Icon
    int iconPct = 101;
    int iconId = -1;
    HashMap<Integer, Integer> iconMap = charging ? maxBatteryChargingToIcon : maxBatteryToIcon;
    for (int key : iconMap.keySet()) {
        if (key < iconPct && batteryPct <= key) {
            iconId = iconMap.get(key);
            iconPct = key;
        }
    }
    ((ImageView) statusBar.findViewById(R.id.battery_icon)).setImageResource(iconId);
}
项目:LucaHome-MediaServer    文件:InfoViewController.java   
@Override
public void onReceive(Context context, Intent intent) {
    if (!_screenEnabled) {
        _logger.Debug("Screen is not enabled!");
        return;
    }

    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
    _batteryValueTextView.setText(String.format("%s%%", level));

    if (level > BAT_LVL_LOW) {
        _batteryAlarmView.setBackgroundResource(R.drawable.circle_green);
    } else if (level <= BAT_LVL_LOW && level > BAT_LVL_CRITICAL) {
        _batteryAlarmView.setBackgroundResource(R.drawable.circle_yellow);
    } else {
        _batteryAlarmView.setBackgroundResource(R.drawable.circle_red);
    }
}
项目:UseCases    文件:CloudStore.java   
private boolean isCharging(@NonNull Context context) {
    boolean charging = false;
    final Intent batteryIntent =
            context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    if (batteryIntent != null) {
        int status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean batteryCharge = status == BatteryManager.BATTERY_STATUS_CHARGING;
        int chargePlug = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
        if (batteryCharge) {
            charging = true;
        }
        if (usbCharge) {
            charging = true;
        }
        if (acCharge) {
            charging = true;
        }
    }
    return charging;
    //        Intent intent = Config.getInstance().getContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    //        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    //        return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
}
项目:smart-scheduler-android    文件:SmartScheduler.java   
/**
 * Method to check if the device is charging.
 *
 * @return Returns true if device is either charging or full, false otherwise
 */
private boolean isCharging() {
    try {
        Intent batteryIntent = mContext.getApplicationContext().registerReceiver(null,
                new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        if (batteryIntent != null) {
            int batteryPowerStatus = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);

            switch (batteryPowerStatus) {
                case BatteryManager.BATTERY_STATUS_CHARGING:
                case BatteryManager.BATTERY_STATUS_FULL:
                    return true;

                case BatteryManager.BATTERY_STATUS_UNKNOWN:
                case BatteryManager.BATTERY_STATUS_DISCHARGING:
                case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                default:
                    return false;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception occurred while isCharging: " + e);
    }

    return false;
}
项目:pearl    文件:UploadDocs.java   
public static boolean isPhonePluggedIn(Context context){
    boolean charging = false;

    final Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean batteryCharge = status==BatteryManager.BATTERY_STATUS_CHARGING;

    int chargePlug = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
    boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

    if (batteryCharge) charging=true;
    if (usbCharge) charging=true;
    if (acCharge) charging=true;

    return charging;
}
项目:batteryhub    文件:DataEstimator.java   
public String getHealthStatus(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;
}
项目:cosu    文件:LockedActivity.java   
private void enableStayOnWhilePluggedIn(boolean enabled){
    if (enabled) {
        mDevicePolicyManager.setGlobalSetting(
                mAdminComponentName,
                Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
                Integer.toString(BatteryManager.BATTERY_PLUGGED_AC
                    | BatteryManager.BATTERY_PLUGGED_USB
                    | BatteryManager.BATTERY_PLUGGED_WIRELESS));
    } else {
        mDevicePolicyManager.setGlobalSetting(
                mAdminComponentName,
                Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
                "0"
                );
    }
}
项目:JobSchedulerCompat    文件:DeviceUtils.java   
public static boolean isCharging(Context context) {
    Bundle extras = getBatteryChangedExtras(context);
    int plugged = extras != null ? extras.getInt(BatteryManager.EXTRA_PLUGGED, 0) : 0;
    return plugged == BatteryManager.BATTERY_PLUGGED_AC
            || plugged == BatteryManager.BATTERY_PLUGGED_USB
            || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1
            && plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS);
}