Example usage for android.content Intent ACTION_BATTERY_CHANGED

List of usage examples for android.content Intent ACTION_BATTERY_CHANGED

Introduction

In this page you can find the example usage for android.content Intent ACTION_BATTERY_CHANGED.

Prototype

String ACTION_BATTERY_CHANGED

To view the source code for android.content Intent ACTION_BATTERY_CHANGED.

Click Source Link

Document

Broadcast Action: This is a sticky broadcast containing the charging state, level, and other information about the battery.

Usage

From source file:org.digitalcampus.oppia.utils.MetaDataUtils.java

private float getBatteryLevel() {
    Intent batteryIntent = ctx.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    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 == -1) {
        return 50.0f;
    }//from  www  . jav  a  2 s. com

    return ((float) level / (float) scale) * 100.0f;
}

From source file:siarhei.luskanau.gps.tracker.free.utils.Utils.java

public static boolean isPowerConnected(Context context) {
    Intent intent = context.getApplicationContext().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;
}

From source file:com.polyvi.xface.extension.XBatteryExt.java

@Override
public XExtensionResult exec(String action, JSONArray args, XCallbackContext callbackCtx) throws JSONException {
    XExtensionResult.Status status = XExtensionResult.Status.INVALID_ACTION;
    String result = "Unsupported Operation: " + action;
    if (COMMAND_START.equals(action)) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        final XCallbackContext cbCtx = callbackCtx;
        if (null == mBroadcastReceiver) {
            mBroadcastReceiver = new BroadcastReceiver() {
                @Override/*from  w  ww  .  j  av  a 2  s.  c om*/
                public void onReceive(Context context, Intent intent) {
                    XLog.d(CLASS_NAME, "received broadcast of battery changing");
                    updateBatteryInfo(intent, cbCtx);
                }
            };
            getContext().registerReceiver(mBroadcastReceiver, intentFilter);
        }
        XExtensionResult extensionResult = new XExtensionResult(XExtensionResult.Status.NO_RESULT);
        extensionResult.setKeepCallback(true);
        return extensionResult;
    } else if (COMMAND_STOP.equals(action)) {
        removeBatteryListener();
        sendUpdate(new JSONObject(), callbackCtx, false);
        return new XExtensionResult(XExtensionResult.Status.OK);
    }
    return new XExtensionResult(status, result);
}

From source file:net.atlaslearning.cordova.OpenIn.OpenIn.java

/**
 * Executes the request./*from  w  ww. java  2s.co m*/
 *
 * @param action           The action to execute.
 * @param args             JSONArry of arguments for the plugin.
 * @param callbackContext    The callback context used when calling back into JavaScript.
 * @return                 True if the action was valid, false if not.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("start")) {
        if (this.batteryCallbackContext != null) {
            callbackContext.error("Battery listener already running.");
            return true;
        }
        this.batteryCallbackContext = callbackContext;

        // We need to listen to power events to update battery status
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        if (this.receiver == null) {
            this.receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    updateBatteryInfo(intent);
                }
            };
            cordova.getActivity().registerReceiver(this.receiver, intentFilter);
        }

        // Don't return any result now, since status results will be sent when events come in from broadcast receiver
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    }

    else if (action.equals("stop")) {
        removeBatteryListener();
        this.sendUpdate(new JSONObject(), false); // release status callback in JS side
        this.batteryCallbackContext = null;
        callbackContext.success();
        return true;
    }

    return false;
}

From source file:org.apache.cordova.batterystatus.BatteryListener.java

/**
 * Executes the request.//w  w w .  j  a  va  2 s.  co m
 *
 * @param action           The action to execute.
 * @param args             JSONArry of arguments for the plugin.
 * @param callbackContext    The callback context used when calling back into JavaScript.
 * @return                 True if the action was valid, false if not.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("start")) {
        if (this.batteryCallbackContext != null) {
            callbackContext.error("Battery listener already running.");
            return true;
        }
        this.batteryCallbackContext = callbackContext;

        // We need to listen to power events to update battery status
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        if (this.receiver == null) {
            this.receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    updateBatteryInfo(intent);
                }
            };
            webView.getContext().registerReceiver(this.receiver, intentFilter);
        }

        // Don't return any result now, since status results will be sent when events come in from broadcast receiver
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    }

    else if (action.equals("stop")) {
        removeBatteryListener();
        this.sendUpdate(new JSONObject(), false); // release status callback in JS side
        this.batteryCallbackContext = null;
        callbackContext.success();
        return true;
    }

    return false;
}

From source file:com.phonegap.BatteryListener.java

/**
 * Executes the request and returns PluginResult.
 * //from  w  w  w  . j ava2 s  .c o  m
 * @param action        The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @param callbackId    The callback id used when calling back into JavaScript.
 * @return              A PluginResult object with a status and message.
 */
public PluginResult execute(String action, JSONArray args, String callbackId) {
    PluginResult.Status status = PluginResult.Status.INVALID_ACTION;
    String result = "Unsupported Operation: " + action;

    if (action.equals("start")) {
        if (this.batteryCallbackId != null) {
            return new PluginResult(PluginResult.Status.ERROR, "Battery listener already running.");
        }
        this.batteryCallbackId = callbackId;

        // We need to listen to power events to update battery status
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        if (this.receiver == null) {
            this.receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    updateBatteryInfo(intent);
                }
            };
            ctx.registerReceiver(this.receiver, intentFilter);
        }

        // Don't return any result now, since status results will be sent when events come in from broadcast receiver 
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        return pluginResult;
    }

    else if (action.equals("stop")) {
        removeBatteryListener();
        this.sendUpdate(new JSONObject(), false); // release status callback in JS side
        this.batteryCallbackId = null;
        return new PluginResult(PluginResult.Status.OK);
    }

    return new PluginResult(status, result);
}

From source file:com.hmatalonga.greenhub.managers.sampling.DataEstimator.java

@Override
public void onReceive(Context context, Intent intent) {
    if (context == null) {
        LOGE(TAG, "Error, context is null");
        return;//from w w w  .j  av a  2  s . com
    }

    if (intent == null) {
        LOGE(TAG, "Data Estimator error, received intent is null");
        return;
    }

    LOGI(TAG, "onReceive action => " + intent.getAction());

    if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
        try {
            level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            mHealth = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0);
            plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
            present = intent.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT);
            status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
            technology = intent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
            temperature = ((float) intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)) / 10;
            voltage = ((float) intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0)) / 1000;
        } catch (RuntimeException e) {
            e.printStackTrace();
        }

        // We don't send battery level alerts here because we need to check if the level changed
        // So we verify that inside the DataEstimator Service

        if (temperature > SettingsUtils.fetchTemperatureWarning(context)) {
            if (SettingsUtils.isBatteryAlertsOn(context) && SettingsUtils.isTemperatureAlertsOn(context)) {

                // Check temperature limit rate
                Calendar lastAlert = Calendar.getInstance();
                long lastSavedTime = SettingsUtils.fetchLastTemperatureAlertDate(context);

                // Set last alert time with saved preferences
                if (lastSavedTime != 0) {
                    lastAlert.setTimeInMillis(lastSavedTime);
                }
                int minutes = SettingsUtils.fetchTemperatureAlertsRate(context);

                lastAlert.add(Calendar.MINUTE, minutes);

                // If last saved time isn't default and now is after limit rate then notify
                if (lastSavedTime == 0 || Calendar.getInstance().after(lastAlert)) {
                    // Notify for temperature alerts...
                    if (temperature > SettingsUtils.fetchTemperatureHigh(context)) {
                        Notifier.batteryHighTemperature(context);
                        SettingsUtils.saveLastTemperatureAlertDate(context, System.currentTimeMillis());
                    } else if (temperature <= SettingsUtils.fetchTemperatureHigh(context)
                            && temperature > SettingsUtils.fetchTemperatureWarning(context)) {
                        Notifier.batteryWarningTemperature(context);
                        SettingsUtils.saveLastTemperatureAlertDate(context, System.currentTimeMillis());
                    }
                }
            }
        }
    }

    // On some phones, scale is always 0.
    if (scale == 0)
        scale = 100;

    if (level > 0) {
        Inspector.setCurrentBatteryLevel(level, scale);

        // Location updates disabled for now
        // requestLocationUpdates();

        // Update last known location...
        // if (lastKnownLocation == null) {
        //    lastKnownLocation = LocationInfo.getLastKnownLocation(context);
        // }

        Intent service = new Intent(context, DataEstimatorService.class);
        service.putExtra("OriginalAction", intent.getAction());
        service.fillIn(intent, 0);

        if (SettingsUtils.isPowerIndicatorShown(context)) {
            LOGI(TAG, "Updating notification status bar");
            Notifier.updateStatusBar(context);
        }

        EventBus.getDefault().post(new BatteryLevelEvent(level));

        startWakefulService(context, service);
    }
}

From source file:com.remobile.batteryStatus.BatteryListener.java

/**
 * Executes the request./*from w w  w. j a  va  2s.c  om*/
 *
 * @param action           The action to execute.
 * @param args             JSONArry of arguments for the plugin.
 * @param callbackContext    The callback context used when calling back into JavaScript.
 * @return                 True if the action was valid, false if not.
 */
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("start")) {
        // We need to listen to power events to update battery status
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        if (this.receiver == null) {
            this.receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    updateBatteryInfo(intent);
                }
            };
            getReactApplicationContext().registerReceiver(this.receiver, intentFilter);
        }

        // Don't return any result now, since status results will be sent when events come in from broadcast receiver
        callbackContext.success();
        return true;
    }

    else if (action.equals("stop")) {
        removeBatteryListener();
        callbackContext.success();
        return true;
    }

    return false;
}

From source file:hmatalonga.greenhub.managers.sampling.DataEstimator.java

@Override
public void onReceive(Context context, Intent intent) {
    if (context == null) {
        LOGE(TAG, "Error, context is null");
        return;/*from  w ww  . j av  a  2  s. co m*/
    }

    if (intent == null) {
        LOGE(TAG, "Data Estimator error, received intent is null");
        return;
    }

    LOGI(TAG, "onReceive action => " + intent.getAction());

    if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
        try {
            level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0);
            plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
            present = intent.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT);
            status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
            technology = intent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
            temperature = ((float) intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)) / 10;
            voltage = ((float) intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0)) / 1000;
        } catch (RuntimeException e) {
            e.printStackTrace();
        }

        if (SettingsUtils.isBatteryAlertsOn(context)) {
            // Notify for temperature alerts...
            if (temperature > 45) {
                Notifier.batteryHighTemperature(context);
            } else if (temperature <= 45 && temperature > 35) {
                Notifier.batteryWarningTemperature(context);
            }
        }

        if (SettingsUtils.isPowerIndicatorShown(context)) {
            Notifier.updateStatusBar(context);
        }
    }

    // On some phones, scale is always 0.
    if (scale == 0)
        scale = 100;

    if (level > 0) {
        Inspector.setCurrentBatteryLevel(level, scale);

        // Location updates disabled for now
        // requestLocationUpdates();

        // Update last known location...
        // if (lastKnownLocation == null) {
        //    lastKnownLocation = LocationInfo.getLastKnownLocation(context);
        // }

        Intent service = new Intent(context, DataEstimatorService.class);
        service.putExtra("OriginalAction", intent.getAction());
        service.fillIn(intent, 0);
        service.putExtra("distance", distance);

        EventBus.getDefault().post(new BatteryLevelEvent(level));

        startWakefulService(context, service);
    }
}

From source file:com.grabtaxi.roadboardscan.zxing.InactivityTimer.java

public synchronized void onResume() {
    if (registered) {
        Log.w(TAG, "PowerStatusReceiver was already registered?");
    } else {/*  w w w  .ja v  a  2 s  .com*/
        activity.registerReceiver(powerStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        registered = true;
    }
    onActivity();
}