Example usage for android.os BatteryManager EXTRA_PLUGGED

List of usage examples for android.os BatteryManager EXTRA_PLUGGED

Introduction

In this page you can find the example usage for android.os BatteryManager EXTRA_PLUGGED.

Prototype

String EXTRA_PLUGGED

To view the source code for android.os BatteryManager EXTRA_PLUGGED.

Click Source Link

Document

Extra for android.content.Intent#ACTION_BATTERY_CHANGED : integer indicating whether the device is plugged in to a power source; 0 means it is on battery, other constants are different types of power sources.

Usage

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

private void monitorBatteryState() {
    battReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            StringBuilder sb = new StringBuilder();

            int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); // charge level from 0 to scale inclusive
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); // Max value for charge level
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, -1);
            boolean present = intent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false);
            int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); //0 if the device is not plugged in; 1 if plugged into an AC power adapter; 2 if plugged in via USB.
            //                int voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1); // voltage in millivolts
            nBatteryTemp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1); // current battery temperature in tenths of a degree Centigrade
            //                String technology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY);

            nChargeLevel = -1; // percentage, or -1 for unknown
            if (rawlevel >= 0 && scale > 0) {
                nChargeLevel = (rawlevel * 100) / scale;
            }//w  w w . j a v a2  s  . c  o  m

            if (plugged > 0)
                sACStatus = "ONLINE";
            else
                sACStatus = "OFFLINE";

            if (present == false)
                sb.append("NO BATTERY");
            else {
                if (nChargeLevel < 10)
                    sb.append("Critical");
                else if (nChargeLevel < 33)
                    sb.append("LOW");
                else if (nChargeLevel > 80)
                    sb.append("HIGH");
            }

            if (BatteryManager.BATTERY_HEALTH_OVERHEAT == health) {
                sb.append("Overheated ");
                sb.append((((float) (nBatteryTemp)) / 10));
                sb.append("(C)");
            } else {
                switch (status) {
                case BatteryManager.BATTERY_STATUS_UNKNOWN:
                    // old emulator; maybe also when plugged in with no battery
                    if (present == true)
                        sb.append(" UNKNOWN");
                    break;
                case BatteryManager.BATTERY_STATUS_CHARGING:
                    sb.append(" CHARGING");
                    break;
                case BatteryManager.BATTERY_STATUS_DISCHARGING:
                    sb.append(" DISCHARGING");
                    break;
                case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                    sb.append(" NOTCHARGING");
                    break;
                case BatteryManager.BATTERY_STATUS_FULL:
                    sb.append(" FULL");
                    break;
                default:
                    if (present == true)
                        sb.append("Unknown");
                    break;
                }
            }

            sPowerStatus = sb.toString();
        }
    };

    IntentFilter battFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(battReceiver, battFilter);
}

From source file:org.restcomm.app.qoslib.Services.Intents.IntentHandler.java

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Bundle intentExtras = intent.getExtras();

    if (owner == null)
        return;//  w w  w. j a  va2s  . com
    owner.getWebSocketManager().sendIntentToWebSocket(action, intentExtras);

    //capture the "battery changed" event
    if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
        DeviceInfoOld.battery = level * 100 / scale;
        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean bCharging = plugged == BatteryManager.BATTERY_PLUGGED_AC
                || plugged == BatteryManager.BATTERY_PLUGGED_USB;
        owner.setBatteryCharging(bCharging);
        dataMonitorStats.setBattery(bCharging, DeviceInfoOld.battery);
    } else if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
        owner.setBatteryCharging(true);
        dataMonitorStats.setBattery(true, null);
    } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
        owner.setBatteryCharging(false);
        dataMonitorStats.setBattery(false, null);
    } else if (action.equals(Intent.ACTION_VIEW)) {
        //this is supposed to trigger the update event
        //owner.triggerUpdateEvent(false, false);
    } else if (action.equals(CommonIntentActionsOld.ACTION_START_UI)) {
        String packagename = intent.getStringExtra("packagename");
        String mypackagename = context.getPackageName();
        PreferenceManager.getDefaultSharedPreferences(context).edit()
                .putString(PreferenceKeys.Miscellaneous.YEILDED_SERVICE, packagename).commit();
        // If the UI started on a different MMC app UI, then we stop this service until this UI is launched
        if (!packagename.equals(mypackagename)) // This will exit the service when safe, and won't restart it because it will be yeilded
            owner.restartSelf();
    } else if (action.equals(UPDATE_ACTION)) {
        owner.getEventManager().triggerUpdateEvent(false, false);
    } else if (action.equals(COLDRESET_ACTION)) {
        //this is supposed to trigger the update event
        owner.getGpsManager().coldStart("triggered by user");
    } else if (action.equals(EMAIL_CSV)) {
        //this is supposed to trigger the update event
        owner.requestCsvEmail();
    } else if (action.equals(SPEED_TEST)) {
        //this is supposed to trigger a speed test
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0);
        //owner.triggerSMSTest(trigger);
        owner.getEventManager().queueActiveTest(EventType.MAN_SPEEDTEST, trigger);
    } else if (action.equals(RUN_WEBSOCKET)) {
        //this is supposed to trigger a speed test
        boolean bStart = intent.getBooleanExtra(EXTRA_START_WEBSOCKET, true);
        owner.getWebSocketManager().runWebSocket(bStart);
        //owner.triggerSpeedTest(trigger);
    } else if (action.equals(ACTIVE_TEST)) {
        //this is supposed to trigger a speed test
        int evType = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_TEST_TYPE, 0);
        EventType eventType = EventType.get(evType);
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0);
        owner.getEventManager().queueActiveTest(eventType, trigger);
    } else if (action.equals(SMS_TEST)) {
        //this is supposed to trigger a speed test
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0);
        //owner.triggerSMSTest(trigger);
        owner.getEventManager().queueActiveTest(EventType.SMS_TEST, trigger);
    } else if (action.contains(SMS_DELIVERED)) {
        //add delivery time to connection history

        int identifier = intent.getIntExtra("identifier", 0); //in case we need to search connection list to find which SMS
        long deliveryTime = 0;

        switch (getResultCode()) {
        case Activity.RESULT_OK:
            deliveryTime = System.currentTimeMillis();
            break;
        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
            deliveryTime = -1;
            break;
        case SmsManager.RESULT_ERROR_NO_SERVICE:
            deliveryTime = -1;
            break;
        case SmsManager.RESULT_ERROR_NULL_PDU:
            deliveryTime = -1;
            break;
        case SmsManager.RESULT_ERROR_RADIO_OFF:
            deliveryTime = -1;
            break;
        }

        owner.getEventManager().handleSMSDeliverNotification(identifier, deliveryTime);
    } else if (action.equals(LATENCY_TEST)) {
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0);
        owner.getEventManager().queueActiveTest(EventType.LATENCY_TEST, trigger);
        //owner.runLatencyTest(false);
    } else if (action.equals(ACTION_STOP_SPEEDTEST)) {
        owner.getEventManager().killSpeedTest();
    } else if (action.equals(ACTION_STOP_VIDEOTEST)) {
        int testType = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_TEST_TYPE, 0);
        owner.getEventManager().killActiveTest(testType);
    } else if (action.equals(ROAMING_ON)) {
        dataMonitorStats.setRoaming(true);
    } else if (action.equals(ROAMING_OFF)) {
        dataMonitorStats.setRoaming(false);
    } else if (action.equals("android.intent.action.ANY_DATA_STATE")) {
        String apn = intentExtras.getString("apn");
        String state = intentExtras.getString("state");
        String apnType = intentExtras.getString("apnType");
        String extras = apnType + "" + state;
        if (state.equals("CONNECTED") && !apnType.equals("default"))
            extras = extras + "!";
        if (apnType != null && apnType.equals("default") && apn != null) {
            SharedPreferences securePref = MainService.getSecurePreferences(context);
            securePref.edit().putString(PreferenceKeys.Miscellaneous.KEY_APN, apn).commit();
        }

    } else if (action.equals("android.intent.action.DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN")) {
        String apn = intentExtras.getString("apn");
        String apnType = intentExtras.getString("apnType");
        String extras = apn + "," + apnType;
    } else if (action.equals("android.intent.action.ACTION_DATA_CONNECTION_FAILED")) {
        String phoneName = intentExtras.getString("phoneName");
        String reason = intentExtras.getString("reason");
        String extras = phoneName + "," + reason;
    } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
        if (owner.getUsageLimits().getDormantMode() > 0)
            return;
        // wifi state change may trigger the event queue to be sent
        //MMCLogger.logToFile(MMCLogger.Level.DEBUG, "MMCIntentHandlerOld", "NETWORK_STATE_CHANGED_ACTION", "");
        owner.wifiStateChange((NetworkInfo) intentExtras.getParcelable(WifiManager.EXTRA_NETWORK_INFO));
        owner.trackAccessPoints(0);
        dataMonitorStats.setWifi(PhoneState.isNetworkWifi(owner));
    } else if (action.equals(WIMAX_STATE_CHANGE)) {
        owner.trackAccessPoints(0);
    } else if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
        //         BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        //         BluetoothClass bclass = device.getBluetoothClass();
        //         int major = bclass.getMajorDeviceClass();
        //         if (major == 1024)
        //            owner.setBTHeadsetState(1);
        //         owner.trackAccessPoints();
    } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED)) {
        owner.trackAccessPoints(0);
    } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
        //         BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        //         BluetoothClass bclass = device.getBluetoothClass();
        //         int major = bclass.getMajorDeviceClass();
        //         if (major == 1024)
        //            owner.setBTHeadsetState(0);
        //         owner.trackAccessPoints();
    } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
        try {
            int state = intent.getIntExtra("state", -1);
            owner.setHeadsetState(state);
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceive",
                    "error receiving Intent.ACTION_HEADSET_PLUG: " + e);
        }
    } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
        int state = intent.getIntExtra("state", -1);
        owner.setHeadsetState(state);
    } else if (action.equals(CommonIntentActionsOld.ACTION_START_VOICETEST)) {
        //this is supposed to trigger a speed test
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_VQ_TRIGGER, 0);
        owner.getVQManager().runTest(trigger);
    } else if (action.equals(CommonIntentActionsOld.ACTION_TEST_VQ_DEVICE)) {
        owner.getVQManager().runTest(10);
    } else if (action.equals(CommonIntentActionsOld.ACTION_STOP_VOICETEST)) {
        owner.getVQManager().killTest();
    } else if (action.equals(RESTART_MMC_SERVICE)) {
        owner.restartNextIdle();

    } else if (action.equals(STOP_TRACKING_ACTION)) {
        owner.getEventManager().stopTracking();
    } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
        try {
            dataMonitorStats.setScreen(false);
            SignalEx mmcSignal = new SignalEx();
            owner.getPhoneStateListener().processNewMMCSignal(mmcSignal);
            if (owner.getTravelDetector() != null) {
                owner.getPhoneState().screenChanged(false);
                owner.getEventManager().screenChanged(false);
            }
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceive",
                    "received action SCREEN_OFF, calling MainService.processNewMMCSignal()", e);
        }
    } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
        dataMonitorStats.setScreen(true);
        if (owner.getTravelDetector() != null) {
            owner.getPhoneState().screenChanged(true);
            owner.getEventManager().screenChanged(true);
        }
    } else if (action.equals(ACTION_ALARM_MINUTE)) {
        // CPU wakes very briefly only in order to spur cellid updates
        owner.getTravelDetector().triggerTravelCheck();
        QosAPI.checkHostApp(context);
    } else if (action.equals(ACTION_TRACKING_5MINUTE)) {
        owner.getTrackingManager().runTracking();
    } else if (action.equals(ACTION_TRACKING_1MINUTE)) {
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceive", "ACTION_TRACKING_1MINUTE");
        owner.getTrackingManager().runTrackingTests();
    } else if (action.equals(ACTION_ALARM_3HOUR)) {
        dataMonitorStats.prepareAllStatistics();
        owner.getEventManager().triggerUpdateEvent(true, false);
        //         Calendar cal = Calendar.getInstance(); 
        //          int hour = cal.get (Calendar.HOUR_OF_DAY); 
        //         //If 12pm to 3 am
        //          if(((hour >= 0 && hour <= 3) || hour == 24) && owner.isNetworkWifi()) {
        //            //See if transit info needs to be downloaded
        //             
        //             //Don't allow the app to shut down until the work is done, keep the CPU running
        //             MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "ACTION_ALARM_3HOUR, wakelock turned on and checking transit "
        //                   + "info uptodate at 24-hour: " + hour);
        //             wakeLock.acquire();
        //             
        //             downloadAreasIfOutOfDate();
        //          }
    }
    //      else if(action.equals(ACTION_TRANSIT_DL_DONE)) {
    //         //Allow CPU to move on
    //         if(wakeLock != null) {
    //            wakeLock.release(); 
    //            MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "received action ACTION_TRANSIT_DONE, wakelock turned off");
    //         }
    //      }
    //      else if(action.equals(ACTION_TRANSIT_DL_START)) {
    //         //Don't allow the app to shut down until the work is done, keep the CPU running
    //          MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "ACTION_TRANSIT_DL_START, wakelock turned on and downloading transit if was requested");
    //          wakeLock.acquire();
    //          
    //          downloadAreasIfOutOfDate();
    //      }
    else if (action.equals(ACTION_ALARM_SCANAPPS)) {
        int intervalDM = PreferenceManager.getDefaultSharedPreferences(owner)
                .getInt(PreferenceKeys.Miscellaneous.MANAGE_DATAMONITOR, 0);
        // run datamonitor if enabled
        if (intervalDM > 0) {
            dataMonitorStats.scanApps();
            dataMonitorStats.getRunningAppsString(false); // for debug
        }

        // Also using this timer for GCM heartbeats (its a 5 minute heartbeat to tell Google Cloud Messaging to check the socket more often for more reliable push messages)
        // 2 independent timers might wake up device twice as often, doubling the battery impact, so I'm forcing it to use one for both cases
        //         boolean useHeartbeat = PreferenceManager.getDefaultSharedPreferences(owner).getBoolean("KEY_GCM_HEARTBEAT", false);
        //         if (useHeartbeat) {
        //            GcmKeepAlive gcm = new GcmKeepAlive(owner);
        //            gcm.broadcastIntents();
        //         }
    } else if (action.equals(ACTION_ALARM_15MINUTE)) {

        int intervalDM = PreferenceManager.getDefaultSharedPreferences(owner)
                .getInt(PreferenceKeys.Miscellaneous.MANAGE_DATAMONITOR, 0);
        // run datamonitor if enabled
        if (intervalDM > 0) {
            boolean firstBucketDone = PreferenceManager.getDefaultSharedPreferences(owner)
                    .getBoolean(PreferenceKeys.Miscellaneous.FIRST_BUCKET, false);
            if (!firstBucketDone) { //if false, first bucket needs to be done
                dataMonitorStats.firstBucket();
                dataMonitorStats.monitor();
                PreferenceManager.getDefaultSharedPreferences(owner).edit()
                        .putBoolean(PreferenceKeys.Miscellaneous.FIRST_BUCKET, true).commit();
                LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, "MMCIntentHandlerOld", "onReceive",
                        "First bucket at: " + System.currentTimeMillis() / 1000);
            } else {
                dataMonitorStats.monitor();
                //MMCLogger.logToFile(MMCLogger.Level.DEBUG, "MMCIntentHandlerOld", "onReceive", "15 min bucket at: " + System.currentTimeMillis()/1000);
            }
        }
        // regardless, still make sure GPS is idle unless needed
        owner.getGpsManager().safeguardGps();
    } else if (action.equals(GPS_STATE_ON)) {
        dataMonitorStats.setGps(true);
    } else if (action.equals(GPS_STATE_OFF)) {
        dataMonitorStats.setGps(false);
    } else if (action.equals(PHONE_CALL_CONNECT)) {
        dataMonitorStats.setPhone(true);
    } else if (action.equals(PHONE_CALL_DISCONNECT)) {
        dataMonitorStats.setPhone(false);
    } else if (action.equals(HANDOFF)) {
        dataMonitorStats.handoff();
    } else if (action.equals(MANUAL_TRANSIT_START)) {
        long lat = intent.getIntExtra("latitude", 0);
        long lon = intent.getIntExtra("longitude", 0);
        Location location = new Location("");
        location.setLatitude(lat / 1000000.0);
        location.setLongitude(lon / 1000000.0);
        location.setAccuracy(-3);

        //         PreferenceManager.getDefaultSharedPreferences(owner).edit().putString(
        //                PreferenceKeys.Miscellaneous.SURVEY_COMMAND,).commit();
        PreferenceManager.getDefaultSharedPreferences(owner).edit()
                .putString("transitEvent", String.valueOf(lat) + "," + String.valueOf(lon)).commit();
        reportManager.manualTransitEvent = owner.getEventManager().triggerSingletonEvent(EventType.MAN_TRANSIT);
        reportManager.manualTransitEvent.setLocation(location, 0);
        owner.getTravelDetector().setTravelling(false);
    } else if (action.equals(MANUAL_TRANSIT_END)) {
        if (reportManager.manualTransitEvent == null)
            return;
        String accelData = intent.getStringExtra("accelerometer");
        int stationFrom = intent.getIntExtra("stationFrom", 0);
        int stationTo = intent.getIntExtra("stationTo", 0);
        int duration = intent.getIntExtra("duration", 0);
        int corrected = intent.getIntExtra("corrected", 0);
        if (corrected != 0) {
            Location location = reportManager.manualTransitEvent.getLocation();
            location.setAccuracy(-4);
        }

        reportManager.manualTransitEvent.setAppData(accelData); //TODO want this to really be in appdata?
        reportManager.manualTransitEvent.setLookupid1(stationFrom);
        reportManager.manualTransitEvent.setLookupid2(stationTo);
        reportManager.manualTransitEvent.setDuration(duration);
        owner.getEventManager().unstageAndUploadEvent(reportManager.manualTransitEvent, null);
        reportManager.manualTransitEvent = null;
    } else if (action.equals(MANUAL_TRANSIT_CANCEL)) {
        if (reportManager.manualTransitEvent != null) {
            owner.getEventManager().unstageEvent(reportManager.manualTransitEvent);
            ReportManager reportManager = ReportManager.getInstance(owner);
            reportManager.getDBProvider().delete(TablesEnum.LOCATIONS.getContentUri(),
                    "timestamp > ? And accuracy = 3",
                    new String[] { String.valueOf(reportManager.manualTransitEvent.getEventTimestamp()) });
            reportManager.manualTransitEvent = null;
        }
    } else if (action.equals(MANUAL_PLOTTING_START)) {
        int floor = intent.getIntExtra("floor", 0);
        //         int type = intent.getIntExtra("type", -1);  //1(indoor) or 2(outdoor)
        int topFloor = intent.getIntExtra("top", -1);
        int lat = intent.getIntExtra("latitude", -1);
        int lng = intent.getIntExtra("longitude", -1);
        long osm_id = intent.getLongExtra("osm_id", 0);
        String poly = intent.getStringExtra("poly");

        reportManager.manualPlottingEvent = owner.getEventManager()
                .triggerSingletonEvent(EventType.MAN_PLOTTING);
        reportManager.manualPlottingEvent.setEventIndex(floor);
        reportManager.manualPlottingEvent.setDuration(topFloor);
        reportManager.manualPlottingEvent.setBuildingID(osm_id);
        reportManager.manualPlottingEvent.setAppData(poly);
        Location location = new Location("");
        location.setLatitude(lat / 1000000.0);
        location.setLongitude(lng / 1000000.0);
        location.setAccuracy(-1);
        reportManager.updateEventField(reportManager.manualPlottingEvent.getLocalID(), "latitude",
                Double.toString(location.getLatitude()));
        reportManager.updateEventField(reportManager.manualPlottingEvent.getLocalID(), "longitude",
                Double.toString(location.getLongitude()));

        reportManager.manualPlottingEvent.setLocation(location, 0);
        presetEventId(reportManager.manualPlottingEvent); // reserve an EventID for this manual sampling event, to be used for Share links

        owner.getTravelDetector().setTravelling(false);
    } else if (action.equals(MANUAL_PLOTTING_END)) {
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceive", "MANUAL_PLOTTING_END");
        //         owner.getEventManager().unstageEvent(manulaPlottingEvent); //does not upload
        if (reportManager.manualPlottingEvent != null)
            owner.getEventManager().unstageAndUploadEvent(reportManager.manualPlottingEvent, null);
        //After the event was submitted, reset it so we don't restore an old event in ManualMapping
        reportManager.manualPlottingEvent = null;
    } else if (action.equals(MANUAL_PLOTTING_CANCEL)) {
        if (reportManager.manualPlottingEvent != null) {
            reportManager.getDBProvider().delete(TablesEnum.LOCATIONS.getContentUri(),
                    "timestamp > ? And accuracy < 0",
                    new String[] { String.valueOf(reportManager.manualPlottingEvent.getEventTimestamp()) });
            reportManager.manualPlottingEvent = null;

        }
    }
    //      else if(intent.getAction().equals(MMS_RECEIVED)) {
    //         LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived MMS_RECEIVED", intentExtras.toString());
    //      }
    //      else if(intent.getAction().equals(MMS_SENT)) {
    //         LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived MMS_SENT", intentExtras.toString());
    //      }
    //      else if(intent.getAction().equals(SMS_REJECTED)) {
    //         LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived SMS_REJECTED", intentExtras.toString());
    //      }
    else if (intent.getAction().equals(SMS_RECEIVED)) {
        SmsMessage[] msgs = null;
        //         String msg_from;
        if (intentExtras == null)
            return;

        Object[] pdus = (Object[]) intentExtras.get("pdus");
        msgs = new SmsMessage[pdus.length];
        String[] msgBody = new String[msgs.length];
        for (int i = 0; i < msgs.length; i++) {
            msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            //            msg_from = msgs[i].getOriginatingAddress();
            String msg = msgs[i].getMessageBody().trim();
            if (msg.length() > 10) {
                msg = msg.substring(1, msg.length() - 1);
                msg = "{" + msg + "}";
            }

            msgBody[i] = msg;

        }
        handleCommands(msgBody, true, 0);
    } else if (action.equals(VIEWING_SIGNAL)) {
        owner.setEnggQueryTime();
    } else if (intent.getAction().equals(SURVEY)) {
        if (intentExtras == null)
            return;

        int surveyid = intentExtras.getInt(SURVEY_EXTRA);
        postSurvey(surveyid);
    } else if (intent.getAction().equals(GCM_MESSAGE)) {
        if (intentExtras == null)
            return;
        try {
            String msg = intentExtras.getString(GCM_MESSAGE_EXTRA);
            long starttime = intentExtras.getLong("GCM_STARTTIME_EXTRA");
            EventResponse eventResponse = gson.fromJson(msg, EventResponse.class);
            eventResponse.init();
            eventResponse.setStartTime(starttime);
            eventResponse.handleEventResponse(owner, true);
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceived GCM_MESSAGE", "exception", e);
        }
    } else if (intent.getAction().equals(COMMAND)) {
        if (intentExtras == null)
            return;

        String commands = intentExtras.getString(COMMAND_EXTRA);
        if (commands == null)
            return;
        long starttime = intent.getLongExtra("STARTTIME_EXTRA", 0);
        String[] msgs = null;
        try {
            JSONArray cmds = new JSONArray(commands);
            msgs = new String[cmds.length()];
            for (int j = 0; j < cmds.length(); j++)
                msgs[j] = cmds.getJSONObject(j).toString();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
        //commands = commands.replace("[", "");
        //commands = commands.replace("]", "");
        //String msgs[] = commands.split("/");
        handleCommands(msgs, false, starttime);
    }

    else if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
        int val = 0;
        val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1);
        String msg = intent.getStringExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE");
        String msg2 = intent.getStringExtra("android.telecom.extra.CALL_DISCONNECT_MESSAGE");
        //MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "String CALL_DISCONNECT_CAUSE", msg);
        //MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "Int CALL_DISCONNECT_CAUSE", ""+val);
    } else if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
        String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        //if (phoneNumber != null)
        //    MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "NEW_OUTGOING_CALL", phoneNumber);
    }

    else if (intent.getAction().equals("android.intent.action.PRECISE_CALL_STATE")) {
        int val = 0;
        //val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1);
        int state_ringing = intent.getIntExtra("ringing_state", -1);
        int state_foreground = intent.getIntExtra("foreground_state", -1);
        int state_background = intent.getIntExtra("background_state", -1);

        int disconnect_cause = intent.getIntExtra("disconnect_cause", -1);
        int precise_disconnect_cause = intent.getIntExtra("precise_disconnect_cause", -1);
        PreciseCallCodes precisecall = new PreciseCallCodes(state_ringing, state_foreground, state_background,
                disconnect_cause, precise_disconnect_cause);
        LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "PRECISE_CALL_STATE", precisecall.toString());
        owner.getPhoneStateListener().onPreciseCallState(precisecall);
    } else if (intent.getAction().equals("android.intent.action.PRECISE_DATA_CONNECTION_STATE_CHANGED")) {
        int val = 0;
        //val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1);
        int state = intent.getIntExtra("state", -1);
        int networkType = intent.getIntExtra("networkType", -1);
        String reason = intent.getStringExtra("reason");
        String failCause = intent.getStringExtra("failCause");
        String apnType = intent.getStringExtra("apnType");
        String apn = intent.getStringExtra("apn");
        Object linkProperties = intent.getParcelableExtra("linkProperties");
        if (!apnType.equals("default"))
            return;
        //         if (failCause != null && failCause.length() > 0)
        //         {
        //            String msg = String.format("state:%d,netType:%d,apnType:%s,reason:%s\r\nfailCause:%s", state,networkType,apnType,reason,failCause);
        //            MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg);
        //            if (linkProperties != null)
        //            {
        //               msg = String.format("PRECISE_DATA_CONNECTION_STATE_CHANGED  linkProperties:%s", linkProperties.toString());
        //               MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg);
        //            }
        //         }
        //         else if (reason != null && reason.length() > 0)
        //         {
        //            String msg = String.format("state:%d,netType:%d,apnType:%s,reason:%s\r\nfailCause:%s", state,networkType,apnType,reason,failCause);
        //            MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg);
        //            if (linkProperties != null)
        //            {
        //               msg = String.format("PRECISE_DATA_CONNECTION_STATE_CHANGED  linkProperties:%s", linkProperties.toString());
        //               MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg);
        //            }
        //         }
    } else if (intent.getAction().equals("org.restcomm.android.CONNECT_FAILED")
            || intent.getAction().equals("org.restcomm.android.CALL_STATE")
            || intent.getAction().equals("org.restcomm.android.DISCONNECT_ERROR")) {
        owner.getPhoneStateListener().getRestCommManager().handleIntent(owner, intent);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_DISCONNECT)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String cause = intent.getStringExtra(EXTRA_RADIOLOG_DISC_CAUSE);
        owner.getPhoneStateListener().onDisconnect(time, cause);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_CONNECT)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String state = intent.getStringExtra(EXTRA_RADIOLOG_CONN_STATE);
        owner.getPhoneStateListener().onConnect(time, state);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_NEIGHBORS)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String neighbors = intent.getStringExtra(EXTRA_RADIOLOG_NEIGHBORS);
        //owner.onConnect(time, state);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_SERVICEMODE)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String jsonstr = intent.getStringExtra(EXTRA_RADIOLOG_SVC_JSON);
        JSONObject json = null;
        try {
            json = new JSONObject(jsonstr);
        } catch (Exception e) {
        }
        String values = intent.getStringExtra(EXTRA_RADIOLOG_SVC_TEXT);
        String name = intent.getStringExtra(EXTRA_RADIOLOG_SVC_NAME);
        owner.getPhoneStateListener().onServiceMode(time, json, values, name);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_SERVICEMENU)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String values = intent.getStringExtra(EXTRA_RADIOLOG_SVC_TEXT);
        String name = intent.getStringExtra(EXTRA_RADIOLOG_SVC_NAME);
        owner.getPhoneStateListener().onServiceMenu(time, values, name);
    } else if (intent.getAction().equals(ACTION_MMCSYS_VERSION)) {
        Integer version = intent.getIntExtra(EXTRA_MMCSYS_VERSION, 0);
        owner.onSvcModeVersion(version);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_ERROR)) {
        String error = intent.getStringExtra(EXTRA_RADIOLOG_ERROR);
        String details = intent.getStringExtra(EXTRA_RADIOLOG_ERROR_DETAIL);
        LoggerUtil.logToFile(LoggerUtil.Level.ERROR, "RilReader", error, details);
        //owner.onConnect(time, state);
    }

}

From source file:de.j4velin.wifiAutoOff.Preferences.java

@SuppressWarnings("deprecation")
@Override//from  w  w w.  j  a v  a  2 s . c  o  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    if (BuildConfig.DEBUG && PermissionChecker.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PermissionChecker.PERMISSION_GRANTED) {
        requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
    }

    status = (StatusPreference) findPreference("status");
    status.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(final Preference preference) {
            WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            boolean connected = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
            if (wm.isWifiEnabled() && !connected) {
                try {
                    startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK)
                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    Toast.makeText(Preferences.this, R.string.settings_not_found_, Toast.LENGTH_SHORT).show();
                }
            } else if (!wm.isWifiEnabled()) {
                wm.setWifiEnabled(true);
            } else {
                try {
                    startActivity(
                            new Intent(Settings.ACTION_WIFI_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    Toast.makeText(Preferences.this, R.string.settings_not_found_, Toast.LENGTH_SHORT).show();
                }
            }
            return true;
        }
    });

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    final CheckBoxPreference screen_off = (CheckBoxPreference) findPreference("off_screen_off");
    screen_off.setSummary(
            getString(R.string.for_at_least, prefs.getInt("screen_off_timeout", Receiver.TIMEOUT_SCREEN_OFF)));

    if (!keepWiFiOn(this)) {
        screen_off.setChecked(false);
    }

    screen_off.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                if (!keepWiFiOn(Preferences.this)) {
                    new AlertDialog.Builder(Preferences.this).setMessage(R.string.sleep_policy)
                            .setPositiveButton(R.string.adv_wifi_settings, new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    try {
                                        startActivity(new Intent(Settings.ACTION_WIFI_IP_SETTINGS)
                                                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                    } catch (Exception e) {
                                        Toast.makeText(Preferences.this, R.string.settings_not_found_,
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }).setNegativeButton(android.R.string.cancel, new OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                    return false;
                }
                if (android.os.Build.VERSION.SDK_INT >= 11) {
                    APILevel11Wrapper.showNumberPicker(Preferences.this, prefs, screen_off,
                            R.string.for_at_least, 1, 60, getString(R.string.minutes_before_turning_off_wifi_),
                            "screen_off_timeout", Receiver.TIMEOUT_SCREEN_OFF, false);
                } else {
                    showPre11NumberPicker(Preferences.this, prefs, screen_off, R.string.for_at_least, 1, 60,
                            getString(R.string.minutes_before_turning_off_wifi_), "screen_off_timeout",
                            Receiver.TIMEOUT_SCREEN_OFF, false);
                }
            }
            return true;
        }
    });

    findPreference("off_no_network").setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                if (android.os.Build.VERSION.SDK_INT >= 11) {
                    APILevel11Wrapper.showNumberPicker(Preferences.this, prefs, preference,
                            R.string.for_at_least, 1, 60, getString(R.string.minutes_before_turning_off_wifi_),
                            "no_network_timeout", Receiver.TIMEOUT_NO_NETWORK, false);
                } else {
                    showPre11NumberPicker(Preferences.this, prefs, preference, R.string.for_at_least, 1, 60,
                            getString(R.string.minutes_before_turning_off_wifi_), "no_network_timeout",
                            Receiver.TIMEOUT_NO_NETWORK, false);
                }
            }
            return true;
        }
    });

    final CheckBoxPreference on_at = (CheckBoxPreference) findPreference("on_at");
    on_at.setTitle(getString(R.string.at_summary, prefs.getString("on_at_time", Receiver.ON_AT_TIME)));
    on_at.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                String[] time = prefs.getString("on_at_time", Receiver.ON_AT_TIME).split(":");
                final TimePickerDialog dialog = new TimePickerDialog(Preferences.this, new OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        prefs.edit().putString("on_at_time",
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)).commit();
                        on_at.setTitle(getString(R.string.at_summary,
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)));
                    }
                }, Integer.parseInt(time[0]), Integer.parseInt(time[1]), true);
                dialog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        on_at.setChecked(false);
                    }
                });
                dialog.setTitle(getString(R.string.turn_wifi_on_at_));
                dialog.show();
            }
            return true;
        }
    });

    final CheckBoxPreference off_at = (CheckBoxPreference) findPreference("off_at");
    off_at.setTitle(getString(R.string.at_summary, prefs.getString("off_at_time", Receiver.OFF_AT_TIME)));
    off_at.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                String[] time = prefs.getString("off_at_time", Receiver.OFF_AT_TIME).split(":");
                final TimePickerDialog dialog = new TimePickerDialog(Preferences.this, new OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        prefs.edit().putString("off_at_time",
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)).commit();
                        off_at.setTitle(getString(R.string.at_summary,
                                hourOfDay + ":" + (minute < 10 ? "0" + minute : minute)));
                    }
                }, Integer.parseInt(time[0]), Integer.parseInt(time[1]), true);
                dialog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        off_at.setChecked(false);
                    }
                });
                dialog.setTitle(getString(R.string.turn_wifi_off_at_));
                dialog.show();
            }
            return true;
        }
    });

    final Preference on_every = findPreference("on_every");
    final String[] time_names = getResources().getStringArray(R.array.time_names);
    // default 2 hours
    on_every.setTitle(getString(R.string.every_summary, prefs.getString("on_every_str", time_names[4])));
    on_every.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((Boolean) newValue) {
                AlertDialog.Builder builder = new AlertDialog.Builder(Preferences.this);
                builder.setTitle(R.string.turn_wifi_on_every).setItems(time_names,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                prefs.edit().putInt("on_every_time_min", time_values[which])
                                        .putString("on_every_str", time_names[which]).commit();
                                on_every.setTitle(getString(R.string.every_summary, time_names[which]));
                            }
                        });
                builder.create().show();
            }
            return true;
        }
    });

    Preference locations = findPreference("locations");
    if (BuildConfig.FLAVOR.equals("play")) {
        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_NETWORK)) {
            locations.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(final Preference preference) {
                    startActivity(new Intent(Preferences.this, Locations.class));
                    return true;
                }
            });
        } else {
            locations.setEnabled(false);
        }
    } else {
        locations.setSummary("Not available in F-Droid version");
        locations.setEnabled(false);
    }

    final Preference power = findPreference("power_connected");
    power.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(final Preference preference, final Object newValue) {
            if ((boolean) newValue) {
                Intent battery = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
                if (battery != null && battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) > 0) {
                    // already connected to external power
                    prefs.edit().putBoolean("ignore_screen_off", true).commit();
                }
            } else {
                prefs.edit().putBoolean("ignore_screen_off", false).commit();
            }
            return true;
        }
    });
}

From source file:saphion.services.ForegroundService.java

public Status readBatteryStat() {
    Intent batteryIntent = getBaseContext().registerReceiver(null,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    int rawlevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    double scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    int plugged = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    isconnected = (plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB
            || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS);
    level = -1;/*from   w  w w.  ja  va  2  s  .c om*/
    if (rawlevel >= 0 && scale > 0) {
        level = (int) ((rawlevel * 100) / scale);
        Log.d("rawLevel: " + rawlevel);
        Log.d("scale: " + scale);
    }

    if (mPref.getBoolean(PreferenceHelper.KEY_ONE_PERCENT_HACK, false)) {
        try {
            java.io.FileReader fReader = new java.io.FileReader(
                    "/sys/class/power_supply/battery/charge_counter");
            java.io.BufferedReader bReader = new java.io.BufferedReader(fReader);
            int charge_counter = Integer.valueOf(bReader.readLine());
            bReader.close();

            if (charge_counter > PreferenceHelper.CHARGE_COUNTER_LEGIT_MAX) {
                disableOnePercentHack("charge_counter is too big to be actual charge");
            } else {
                if (charge_counter > 100)
                    charge_counter = 100;

                level = charge_counter;
            }
        } catch (java.io.FileNotFoundException e) {
            /*
             * These error messages are only really useful to me and might
             * as well be left hardwired here in English.
             */
            disableOnePercentHack("charge_counter file doesn't exist");
        } catch (java.io.IOException e) {
            disableOnePercentHack("Error reading charge_counter file");
        }
    }

    return new Status(level, isconnected);
}

From source file:org.metawatch.manager.Monitors.java

private static void createBatteryLevelReciever(Context context) {
    if (batteryLevelReceiver != null)
        return;//from ww  w . ja va  2 s. co  m

    batteryLevelReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            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;
            }
            boolean charging = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) > 0;
            if (BatteryData.level != level || BatteryData.charging != charging) {
                //if (Preferences.logging) Log.d(MetaWatch.TAG, "Battery level changed: "+rawlevel+"/"+scale+" - "+level+"%");
                BatteryData.level = level;
                BatteryData.charging = charging;
                Idle.updateIdle(context, true);
            }
        }
    };
    context.registerReceiver(batteryLevelReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

From source file:saphion.services.ForegroundService.java

public int readbattery() {
    Intent batteryIntent = getApplicationContext().registerReceiver(null,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    int rawlevel = batteryIntent.getIntExtra("level", -1);
    double scale = batteryIntent.getIntExtra("scale", -1);
    int plugged = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    isconnected = (plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB
            || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS);
    level = -1;//from  www  .ja va 2 s .  co  m
    if (rawlevel >= 0 && scale > 0) {
        level = (int) ((rawlevel * 100) / scale);
        Log.d("rawLevel: " + rawlevel);
        Log.d("scale: " + scale);
    }

    temperature = Functions.updateTemperature(
            (float) ((float) (batteryIntent.getIntExtra("temperature", 0)) / 10),
            mPref.getBoolean(PreferenceHelper.MAIN_TEMP, true), true);

    int inthealth = batteryIntent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0);
    health = "";
    switch (inthealth) {
    case BatteryManager.BATTERY_HEALTH_COLD:
        health = "Cold";
        break;
    case BatteryManager.BATTERY_HEALTH_DEAD:
        health = "Dead";
        break;
    case BatteryManager.BATTERY_HEALTH_GOOD:
        health = "Good";
        break;
    case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
        health = "Over Voltage";
        break;
    case BatteryManager.BATTERY_HEALTH_OVERHEAT:
        health = "Overheat";
        break;
    case BatteryManager.BATTERY_HEALTH_UNKNOWN:
        health = "Unknown";
        break;
    case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
        health = "Unspecified failure";
        break;
    }

    if (mPref.getBoolean(PreferenceHelper.KEY_ONE_PERCENT_HACK, false)) {
        try {
            java.io.FileReader fReader = new java.io.FileReader(
                    "/sys/class/power_supply/battery/charge_counter");
            java.io.BufferedReader bReader = new java.io.BufferedReader(fReader);
            int charge_counter = Integer.valueOf(bReader.readLine());
            bReader.close();

            if (charge_counter > PreferenceHelper.CHARGE_COUNTER_LEGIT_MAX) {
                disableOnePercentHack("charge_counter is too big to be actual charge");
            } else {
                if (charge_counter > 100)
                    charge_counter = 100;

                level = charge_counter;
            }
        } catch (java.io.FileNotFoundException e) {
            /*
             * These error messages are only really useful to me and might
             * as well be left hardwired here in English.
             */
            disableOnePercentHack("charge_counter file doesn't exist");
        } catch (java.io.IOException e) {
            disableOnePercentHack("Error reading charge_counter file");
        }
    }

    return level;
}

From source file:org.mariotaku.twidere.util.Utils.java

public static boolean isBatteryOkay(final Context context) {
    if (context == null)
        return false;
    final Context app = context.getApplicationContext();
    final IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    final Intent intent = app.registerReceiver(null, filter);
    if (intent == null)
        return false;
    final boolean plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) > 0;
    final float level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
    final float scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
    return plugged || level / scale > 0.15f;
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static boolean isBatteryOkay(final Context context) {
    if (context == null)
        return false;
    final Context app = context.getApplicationContext();
    final IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    final Intent intent = app.registerReceiver(null, filter);
    if (intent == null)
        return false;
    final boolean plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;
    final float level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
    final float scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
    return plugged || level / scale > 0.15f;
}