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:io.rapidpro.androidchannel.RapidPro.java

@Override
public void onCreate() {
    super.onCreate();

    PreferenceManager.setDefaultValues(this, R.layout.settings, false);

    // earlier versions of android are allowed to have higher message throughput
    // before Build.VERSION_CODES.ICE_CREAM_SANDWICH which is 14
    if (Build.VERSION.SDK_INT < 14) {
        MESSAGE_THROTTLE = 100;/*from w  w  w.j a va 2 s . c  om*/
        MESSAGE_THROTTLE_MINUTES = 60;
        MESSAGE_THROTTLE_WINDOW = 1000 * 60 * (MESSAGE_THROTTLE_MINUTES + 2);
    }

    s_this = this;

    // register our sms modem
    m_modem = new SMSModem(this, new SMSListener());

    // register our Incoming SMS listener
    m_incomingSMSObserver = new IncomingSMSObserver();
    getContentResolver().registerContentObserver(Uri.parse("content://sms"), true, m_incomingSMSObserver);

    // register our call listener
    m_callObserver = new CallObserver();
    getContentResolver().registerContentObserver(Calls.CONTENT_URI, true, m_callObserver);

    // register for device details
    IntentFilter statusChanged = new IntentFilter();
    statusChanged.addAction(Intent.ACTION_BATTERY_CHANGED);
    statusChanged.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

    StatusReceiver receiver = new StatusReceiver();
    getBaseContext().registerReceiver(receiver, statusChanged);

    WakefulIntentService.cancelAlarms(this);
    WakefulIntentService.scheduleAlarms(new RapidProAlarmListener(), this);

    refreshInstalledPacks();

    updateNotification();
}

From source file:org.openchaos.android.fooping.service.PingService.java

@Override
protected void onHandleIntent(Intent intent) {
    String clientID = prefs.getString("ClientID", "unknown");
    long ts = System.currentTimeMillis();

    Log.d(tag, "onHandleIntent()");

    // always send ping
    if (true) {//from  w  w  w  . j a v a  2 s .  co m
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "ping");
            json.put("ts", ts);

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/training/monitoring-device-state/battery-monitoring.html
    // http://developer.android.com/reference/android/os/BatteryManager.html
    if (prefs.getBoolean("UseBattery", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "battery");
            json.put("ts", ts);

            Intent batteryStatus = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            if (batteryStatus != null) {
                JSONObject bat_data = new JSONObject();

                int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                if (level >= 0 && scale > 0) {
                    bat_data.put("pct", roundValue(((double) level / (double) scale) * 100, 2));
                } else {
                    Log.w(tag, "Battery level unknown");
                    bat_data.put("pct", -1);
                }
                bat_data.put("health", batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH, -1));
                bat_data.put("status", batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1));
                bat_data.put("plug", batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1));
                bat_data.put("volt", batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1));
                bat_data.put("temp", batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1));
                bat_data.put("tech", batteryStatus.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY));
                // bat_data.put("present", batteryStatus.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false));

                json.put("battery", bat_data);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/guide/topics/location/strategies.html
    // http://developer.android.com/reference/android/location/LocationManager.html
    if (prefs.getBoolean("UseGPS", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "loc_gps");
            json.put("ts", ts);

            if (lm == null) {
                lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            }

            Location last_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (last_loc != null) {
                JSONObject loc_data = new JSONObject();

                loc_data.put("ts", last_loc.getTime());
                loc_data.put("lat", last_loc.getLatitude());
                loc_data.put("lon", last_loc.getLongitude());
                if (last_loc.hasAltitude())
                    loc_data.put("alt", roundValue(last_loc.getAltitude(), 4));
                if (last_loc.hasAccuracy())
                    loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4));
                if (last_loc.hasSpeed())
                    loc_data.put("speed", roundValue(last_loc.getSpeed(), 4));
                if (last_loc.hasBearing())
                    loc_data.put("bearing", roundValue(last_loc.getBearing(), 4));

                json.put("loc_gps", loc_data);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    if (prefs.getBoolean("UseNetwork", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "loc_net");
            json.put("ts", ts);

            if (lm == null) {
                lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            }

            Location last_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (last_loc != null) {
                JSONObject loc_data = new JSONObject();

                loc_data.put("ts", last_loc.getTime());
                loc_data.put("lat", last_loc.getLatitude());
                loc_data.put("lon", last_loc.getLongitude());
                if (last_loc.hasAltitude())
                    loc_data.put("alt", roundValue(last_loc.getAltitude(), 4));
                if (last_loc.hasAccuracy())
                    loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4));
                if (last_loc.hasSpeed())
                    loc_data.put("speed", roundValue(last_loc.getSpeed(), 4));
                if (last_loc.hasBearing())
                    loc_data.put("bearing", roundValue(last_loc.getBearing(), 4));

                json.put("loc_net", loc_data);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/reference/android/net/wifi/WifiManager.html
    if (prefs.getBoolean("UseWIFI", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "wifi");
            json.put("ts", ts);

            if (wm == null) {
                wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            }

            List<ScanResult> wifiScan = wm.getScanResults();
            if (wifiScan != null) {
                JSONArray wifi_list = new JSONArray();

                for (ScanResult wifi : wifiScan) {
                    JSONObject wifi_data = new JSONObject();

                    wifi_data.put("BSSID", wifi.BSSID);
                    wifi_data.put("SSID", wifi.SSID);
                    wifi_data.put("freq", wifi.frequency);
                    wifi_data.put("level", wifi.level);
                    // wifi_data.put("cap", wifi.capabilities);
                    // wifi_data.put("ts", wifi.timestamp);

                    wifi_list.put(wifi_data);
                }

                json.put("wifi", wifi_list);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // TODO: cannot poll sensors. register receiver to cache sensor data
    // http://developer.android.com/guide/topics/sensors/sensors_overview.html
    // http://developer.android.com/reference/android/hardware/SensorManager.html
    if (prefs.getBoolean("UseSensors", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "sensors");
            json.put("ts", ts);

            if (sm == null) {
                sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            }

            List<Sensor> sensors = sm.getSensorList(Sensor.TYPE_ALL);
            if (sensors != null) {
                JSONArray sensor_list = new JSONArray();

                for (Sensor sensor : sensors) {
                    JSONObject sensor_info = new JSONObject();

                    sensor_info.put("name", sensor.getName());
                    sensor_info.put("type", sensor.getType());
                    sensor_info.put("vendor", sensor.getVendor());
                    sensor_info.put("version", sensor.getVersion());
                    sensor_info.put("power", roundValue(sensor.getPower(), 4));
                    sensor_info.put("resolution", roundValue(sensor.getResolution(), 4));
                    sensor_info.put("range", roundValue(sensor.getMaximumRange(), 4));

                    sensor_list.put(sensor_info);
                }

                json.put("sensors", sensor_list);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
    // http://developer.android.com/reference/android/net/ConnectivityManager.html
    if (prefs.getBoolean("UseConn", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "conn");
            json.put("ts", ts);

            if (cm == null) {
                cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            }

            // TODO: add active/all preferences below UseConn
            if (prefs.getBoolean("UseConnActive", true)) {
                NetworkInfo net = cm.getActiveNetworkInfo();
                if (net != null) {
                    JSONObject net_data = new JSONObject();

                    net_data.put("type", net.getTypeName());
                    net_data.put("subtype", net.getSubtypeName());
                    net_data.put("connected", net.isConnected());
                    net_data.put("available", net.isAvailable());
                    net_data.put("roaming", net.isRoaming());
                    net_data.put("failover", net.isFailover());
                    if (net.getReason() != null)
                        net_data.put("reason", net.getReason());
                    if (net.getExtraInfo() != null)
                        net_data.put("extra", net.getExtraInfo());

                    json.put("conn_active", net_data);
                }
            }

            if (prefs.getBoolean("UseConnAll", false)) {
                NetworkInfo[] nets = cm.getAllNetworkInfo();
                if (nets != null) {
                    JSONArray net_list = new JSONArray();

                    for (NetworkInfo net : nets) {
                        JSONObject net_data = new JSONObject();

                        net_data.put("type", net.getTypeName());
                        net_data.put("subtype", net.getSubtypeName());
                        net_data.put("connected", net.isConnected());
                        net_data.put("available", net.isAvailable());
                        net_data.put("roaming", net.isRoaming());
                        net_data.put("failover", net.isFailover());
                        if (net.getReason() != null)
                            net_data.put("reason", net.getReason());
                        if (net.getExtraInfo() != null)
                            net_data.put("extra", net.getExtraInfo());

                        net_list.put(net_data);
                    }

                    json.put("conn_all", net_list);
                }
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    if (!PingServiceReceiver.completeWakefulIntent(intent)) {
        Log.w(tag, "completeWakefulIntent() failed. no active wake lock?");
    }
}

From source file:org.opensilk.music.ui2.LauncherActivity.java

@Override
protected void onStart() {
    super.onStart();
    mPluginConnectionManager.onResume();
    if (RxUtils.notSubscribed(chargingSubscription)) {
        //check if already plugged first
        IntentFilter filter2 = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent battChanged = registerReceiver(null, filter2);
        int battStatus = (battChanged != null) ? battChanged.getIntExtra(BatteryManager.EXTRA_STATUS, -1) : -1;
        if (battStatus == BatteryManager.BATTERY_STATUS_CHARGING
                || battStatus == BatteryManager.BATTERY_STATUS_FULL) {
            keepScreenOn(true);// ww  w  . j a  v  a 2 s. c  o m
        }
        // keep apprised of future plug events
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_POWER_CONNECTED);
        filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        chargingSubscription = AndroidObservable.fromBroadcast(this, filter).subscribe(new Action1<Intent>() {
            @Override
            public void call(Intent intent) {
                if (Intent.ACTION_POWER_CONNECTED.equals(intent.getAction())) {
                    keepScreenOn(true);
                } else if (Intent.ACTION_POWER_DISCONNECTED.equals(intent.getAction())) {
                    keepScreenOn(false);
                }
            }
        });
    }
}

From source file:org.wso2.emm.system.service.api.OTADownload.java

private int getBatteryLevel(Context context) {
    Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int level = 0;
    if (batteryIntent != null) {
        level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
    }/*from  w  ww  .ja  va  2 s . c  om*/

    return level;
}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.SystemMonitor.java

@Override
public void onCreate() {
    super.onCreate();
    // Use filter for Monitor Significant Changes in Battery Level only
    // Generally speaking, the impact of constantly monitoring the
    // battery//  www .  j  a  v  a2  s .  com
    // level has a greater impact on the battery than your app's normal
    // behavior, so it's good practice to only monitor significant
    // changes
    // in battery levelspecifically when the device enters or exits a
    // low
    // battery state.
    IntentFilter ifilter = new IntentFilter();
    ifilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    // ifilter.addAction(Intent.ACTION_BATTERY_OKAY);
    this.registerReceiver(batteryLvlReceiver, ifilter);

    // get Location
    MyLocation myLocation = new MyLocation();
    myLocation.getLocation(this, locationResult);

    // scheduleNextUpdate();

    // Notify user of this service
    //      systemNotice();

    this.stopSelf();

}

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

public void getCurrentStatus(final Context context) {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = context.registerReceiver(null, ifilter);
    assert batteryStatus != null;

    level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    health = 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);
}

From source file:edu.utexas.quietplaces.services.PlacesUpdateService.java

/**
 * {@inheritDoc}//w w  w .j av  a  2 s. c  o  m
 * Checks the battery and connectivity state before removing stale venues
 * and initiating a server poll for new venues around the specified
 * location within the given radius.
 */
@Override
protected void onHandleIntent(Intent intent) {
    // Check if we're running in the foreground, if not, check if
    // we have permission to do background updates.
    //noinspection deprecation
    boolean backgroundAllowed = cm.getBackgroundDataSetting();
    boolean inBackground = prefs.getBoolean(PlacesConstants.EXTRA_KEY_IN_BACKGROUND, true);

    if (!backgroundAllowed && inBackground)
        return;

    // Extract the location and radius around which to conduct our search.
    Location location = new Location(PlacesConstants.CONSTRUCTED_LOCATION_PROVIDER);
    int radius = PlacesConstants.PLACES_SEARCH_RADIUS;

    Bundle extras = intent.getExtras();
    if (intent.hasExtra(PlacesConstants.EXTRA_KEY_LOCATION)) {
        location = (Location) (extras.get(PlacesConstants.EXTRA_KEY_LOCATION));
        radius = extras.getInt(PlacesConstants.EXTRA_KEY_RADIUS, PlacesConstants.PLACES_SEARCH_RADIUS);
    }

    // Check if we're in a low battery situation.
    IntentFilter batIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent battery = registerReceiver(null, batIntentFilter);
    lowBattery = getIsLowBattery(battery);

    // Check if we're connected to a data network, and if so - if it's a mobile network.
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    mobileData = activeNetwork != null && activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE;

    // If we're not connected, enable the connectivity receiver and disable the location receiver.
    // There's no point trying to poll the server for updates if we're not connected, and the
    // connectivity receiver will turn the location-based updates back on once we have a connection.
    if (!isConnected) {
        Log.w(TAG, "Not connected!");
    } else {
        // If we are connected check to see if this is a forced update (typically triggered
        // when the location has changed).
        boolean doUpdate = intent.getBooleanExtra(PlacesConstants.EXTRA_KEY_FORCEREFRESH, false);

        // If it's not a forced update (for example from the Activity being restarted) then
        // check to see if we've moved far enough, or there's been a long enough delay since
        // the last update and if so, enforce a new update.
        if (!doUpdate) {
            // Retrieve the last update time and place.
            long lastTime = prefs.getLong(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_TIME, Long.MIN_VALUE);
            float lastLat;
            try {
                lastLat = prefs.getFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LAT, Float.MIN_VALUE);
            } catch (ClassCastException e) {
                // handle legacy version
                lastLat = Float.MIN_VALUE;
            }
            float lastLng;
            try {
                lastLng = prefs.getFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LNG, Float.MIN_VALUE);
            } catch (ClassCastException e) {
                lastLng = Float.MIN_VALUE;
            }
            Location lastLocation = new Location(PlacesConstants.CONSTRUCTED_LOCATION_PROVIDER);
            lastLocation.setLatitude(lastLat);
            lastLocation.setLongitude(lastLng);

            long currentTime = System.currentTimeMillis();
            float distanceMovedSinceLast = lastLocation.distanceTo(location);
            long elapsedTime = currentTime - lastTime;

            Log.i(TAG, "Last Location in places update service: " + lastLocation + " distance to current: "
                    + distanceMovedSinceLast + " - current: " + location);

            if (location == null) {
                Log.w(TAG, "Location is null...");
            }
            // If update time and distance bounds have been passed, do an update.
            else if (lastTime < currentTime - PlacesConstants.MAX_TIME_BETWEEN_PLACES_UPDATE) {
                Log.i(TAG, "Time bounds passed on places update, " + elapsedTime / 1000 + "s elapsed");
                doUpdate = true;
            } else if (distanceMovedSinceLast > PlacesConstants.MIN_DISTANCE_TRIGGER_PLACES_UPDATE) {
                Log.i(TAG, "Distance bounds passed on places update, moved: " + distanceMovedSinceLast
                        + " meters, time elapsed:  " + elapsedTime / 1000 + "s");
                doUpdate = true;
            } else {
                Log.d(TAG, "Time/distance bounds not passed on places update. Moved: " + distanceMovedSinceLast
                        + " meters, time elapsed: " + elapsedTime / 1000 + "s");
            }
        }

        if (location == null) {
            Log.e(TAG, "null location in onHandleIntent");
        } else if (doUpdate) {
            // Refresh the prefetch count for each new location.
            prefetchCount = 0;
            // Remove the old locations - TODO: we flush old locations, but if the next request
            // fails we are left high and dry
            removeOldLocations(location, radius);
            // Hit the server for new venues for the current location.
            refreshPlaces(location, radius, null);

            // Tell the main activity about the new results.
            Intent placesUpdatedIntent = new Intent(Config.ACTION_PLACES_UPDATED);
            LocalBroadcastManager.getInstance(this).sendBroadcast(placesUpdatedIntent);

        } else {
            Log.i(TAG, "Place List is fresh: Not refreshing");
        }

        // Retry any queued checkins.
        /*
                    Intent checkinServiceIntent = new Intent(this, PlaceCheckinService.class);
                    startService(checkinServiceIntent);
        */
    }
    Log.d(TAG, "Place List Download Service Complete");
}

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

public static Intent getBatteryChangedIntent(final Context context) {
    return context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

From source file:gpsalarm.app.service.PostMonitor.java

@Override
public void onCreate() {
    super.onCreate();
    sdb = new TimelineHelper(this);
    rdb = new ReminderHelper(this);

    //get user account from preference.
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    team = prefs.getString("team", "").toUpperCase();
    myAccount = new Account(prefs.getString("user", null), prefs.getString("password", ""), null);

    registerReceiver(onBatteryChanged, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, OnAlarmReceiver.class);
    pi = PendingIntent.getBroadcast(this, 0, i, 0);
    setAlarm(INITIAL_POLL_PERIOD);/*from   w  w  w .  j a  v a2s. c  o  m*/
}

From source file:fr.free.coup2lapan.ActualStateActivity.java

public BatteryStat getBatteryStatus() {

    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent status = this.registerReceiver(null, ifilter);

    BatteryStat batterystat = new BatteryStat(status.getIntExtra(BatteryManager.EXTRA_LEVEL, 0),
            status.getIntExtra(BatteryManager.EXTRA_SCALE, 0),
            status.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0),
            status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0),
            status.getIntExtra(BatteryManager.EXTRA_STATUS, 0),
            status.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0),
            status.getIntExtra(BatteryManager.EXTRA_HEALTH, 0),
            status.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT) ? 1 : 0,
            DateFormat.getDateInstance(2, localeFR).format(new Date())
                    + DateFormat.getTimeInstance(2, localeFR).format(new Date()),
            status.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY));

    return batterystat;
}